Search This Blog

Thursday, 17 October 2013

form-login Custom Options

In the previous post we saw how to set the login page as a custom one. There are other configuration options available too. For instance:
<form-login login-page="/login.jsp" authentication-failure-url="loginError.jsp"/>
If now login fails, then user will be redirected to the above failure URL. Consider the logs generated when I entered invalid credentials:

DEBUG DaoAuthenticationProvider:134 - User 'r' not found
DEBUG UsernamePasswordAuthenticationFilter:346 - Authentication request failed: Bad credentials
DEBUG UsernamePasswordAuthenticationFilter:347 - Updated SecurityContextHolder 
to contain null Authentication
DEBUG UsernamePasswordAuthenticationFilter:348 - Delegating to authentication failure 
DEBUG SimpleUrlAuthenticationFailureHandler:67 - Redirecting to /loginError.jsp
DEBUG DefaultRedirectStrategy:36 - Redirecting to '/FormLogin/loginError.jsp'
In the previous post we saw how Spring redirected us to login when we tried to access a secure URL. On successful login, Spring automatically redirected us to the requested resource. This worked because Spring held the resource requested as a session attribute. But what if we want to prevent this behavior ? For example I would like that all users to my website start on the account summary page on login. The form-login element provides support for the same:
<form-login login-page="/login.jsp" always-use-default-target="true" 
      default-target-url="/dynamic/account.jsp" />
Any successful login now will redirect to the above page.
2013-07-15 19:00:01 DEBUG HttpSessionRequestCache:62 - Removing DefaultSavedRequest from session if present
2013-07-15 19:00:01 DEBUG DefaultRedirectStrategy:36 - Redirecting to '/FormLogin/dynamic/account.jsp'
Lastly we can configure even the entire login page. Consider the form-login element:
<form-login login-page="/customLogin.jsp" login-processing-url="/login"
    password-parameter="pwd" username-parameter="user" />
This will work with the html form as :
<form method="POST" action="${pageContext.request.contextPath}/login">
  <table style="border: 1 px grey;">
      <td>User name</td>
        <input type="text" name="user">
        <input type="password" name="pwd">
As seen here the login URL used is not "j_spring_security_check" but "/login". Also the form fields have their own unique names. The login flow will continue to work as before.

No comments:

Post a Comment