2

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?

user815806
  • 43
  • 3

1 Answers1

1

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')}" />
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Thanks BalusC. What happens in #{auth.login}? Can that method trigger a j_security_check and re-render the same page? The optional rendering wasn't the question (but thank you nonetheless), but how to use j_security_check to force a login in #{auth.login} and return to the same page after login. And if that can't be done using j_security_check, what is the preferred way to do it? Thank you again. – user815806 Nov 28 '12 at 21:44
  • See the "programmatic login" part of this answer: http://stackoverflow.com/questions/2206911/best-way-for-user-authentication-on-javaee-6-using-jsf-2-0/2207147#2207147 It boils down to manually calling `HttpServletRequest#login()` with the supplied credentials. – BalusC Nov 28 '12 at 22:05
  • Checked it out. Perfectly answers the question. Thanks again. – user815806 Nov 29 '12 at 00:24