Question

In a JSF2 / Java EE 6 web application using container-managed security, form-based authentication (j_security_check) requires a protected page to be requested, after which the container handles the login process for you, redirecting the browser to the requested page once authenticated.

There are many common scenarios where this is not how you want your application to behave. For example, you might want to have a read-only version and an updateable version of the same page. You might put a "login now to edit" button on that page if the user is not logged in, and make the fields editable if the user is logged in. But its the same JSF page in both situations, and that view can't be both unprotected and protected, so j_security_check would not seem to handle this scenario.

So, two questions:

1) Can j_security_check be manipulated into achieving this functionality? or 2) What is the "normal" way JSF / JavaEE webapps achieve this if j_security_check can't?

Was it helpful?

Solution

The logged-in user is also available in unsecured pages. You could just perform a logged-in check by checking the presence of HttpServletRequest#getRemoteUser() and a role check by HttpServletRequest#isUserInRole() and render restricted components accordingly.

E.g., show "login to edit" button only when user isn't logged in:

<h:commandButton 
    value="Login to edit" action="#{auth.login}" 
    rendered="#{empty request.remoteUser}" />

And show "edit" button only when user is logged in, or has the desired role:

<h:commandButton 
    value="Edit" action="#{someBean.edit(someItem)}" 
    rendered="#{not empty request.remoteUser}" />
<!-- or -->
<h:commandButton 
    value="Edit" action="#{someBean.edit(someItem)}" 
    rendered="#{request.isUserInRole('ADMIN')}" />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top