Search This Blog

Friday 22 November 2013

Remember Me... Spring Security

Login page in most web applications have a small check-box that says "Remember Me". Nothing new there. The cool part is spring security comes with this functionality ready made.
I decided to use the default login form to test the feature:

<http>
    <intercept-url pattern="/dynamic/**" access="ROLE_USER" />
    <intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
    <form-login />
    <logout logout-success-url="/out.html" />
    <remember-me />
  </http>
The default login page will now show a small checkbox too:
<tr>
  <td>
    <input type='checkbox' name='_spring_security_remember_me' />
  </td>
  <td>Remember me on this computer.</td>
</tr>
On login the sever logs indicate :
2013-07-15 20:34:48 DEBUG SessionFixationProtectionStrategy:98 - Started new session: B8D55B678749009B8DB559E54369A5B8
  2013-07-15 20:34:48 DEBUG UsernamePasswordAuthenticationFilter:317 - Authentication success.
  2013-07-15 20:34:48 DEBUG TokenBasedRememberMeServices:197 - Added remember-me cookie for user 'robin',
 expiry: 'Mon Jul 29 20:34:48 IST 2013'
As seen the code created a cookie with a life span of 14 days. The cookie is set to the response. The next time when the user tries to navigate a secure URL(after expiry of current session):
2013-07-16 13:50:20 DEBUG HttpSessionSecurityContextRepository:127 - No HttpSession currently exists
...
2013-07-16 13:50:20 DEBUG TokenBasedRememberMeServices:103 - Remember-me cookie detected
2013-07-16 13:50:20 DEBUG TokenBasedRememberMeServices:118 - Remember-me cookie accepted
2013-07-16 13:50:20 DEBUG ProviderManager:152 - Authentication attempt using 
org.springframework.security.authentication.RememberMeAuthenticationProvider
2013-07-16 13:50:20 DEBUG RememberMeAuthenticationFilter:110 - SecurityContextHolder 
populated with remember-me token:...
...
2013-07-16 13:50:20 DEBUG FilterSecurityInterceptor:215 - Authorization successful
As seen based on the details present in the remember-me cookie, the user was authenticated and then allowed to view the page as authorization requirements were met. The format for the cookie value is :
Base64Encode(username + ":" + expiryTime + ":" 
       + Md5Hex(username + ":" + expiryTime + ":" + password + ":" + key))
The response header for the login call indicates the same:
Set-Cookie:SPRING_SECURITY_REMEMBER_ME_COOKIE=
cm9iaW46MTM3NTE3MzAyNjQ1MzplZDhjZWM5YWJiZTE1MzdiMTVmNjQ4NzQ4ZjM1YWE1ZA;
Expires=Tue, 30-Jul-2013 08:30:26 GMT; Path=/FormLogin; HttpOnly
Can we customize the cookie settings ?
Yes the key validity and time to expire can be configured via XML:
<remember-me key="appRKey" token-validity-seconds="12000" />
More on these and other attribute later.

1 comment:

  1. I think this is a really good article. You make this information interesting and engaging. You give readers a lot to think about and I appreciate that kind of writing. 사설토토

    ReplyDelete