Mahoni
Mahoni

Reputation: 7466

How can I check for authorization in JAAS during request

I have implemented form authentication as offered by JAAS. Since I process all my pages as templates code has to be evaluated every time. Thus when the user is directo to /login the doGet request has to handle it and process the login template.

Now I would like to redirect to the main page after the login was successful. When the user chooses /login again he/she should be redirected to the main page.

Thus I need to know during a doGet request whether the user is authorized, maybe also which authentication. How can I check? Or is this idiom wrong?


Or is this done by request.isUserInRole(String role)? Since it does both, authentication AND authorization?

Upvotes: 1

Views: 1611

Answers (1)

BalusC
BalusC

Reputation: 1108642

You can check if an user is logged in by checking if HttpServletRequest#getRemoteUser() (the user name) or #getUserPrincipal() (the associated Princpal object) does not return null.

So, e.g. in doGet() of the /login servlet you could do this:

if (request.getRemoteUser() != null) {
    // Already logged in, so redirect to some main page.
    response.sendRedirect(request.getContextPath() + "/main");
    return;
}

// ...

The #isUserInRole() only checks if the logged-in user has some specific role and this is usually only useful to restrict some pages or page sections for specific roles. So unless you've a general role which is shared by every user, this isn't useful.

You may only want to add a message to inform the enduser why s/he is been redirected and what's the proper way to login again as another user. E.g. "You are already logged in. If you need to login as another user, please go to logout page first." or so in the main page which is conditionally displayed based on some redirect parameter.

Upvotes: 3

Related Questions