Follow the post about Spring Security, in this post I will guide how to implement Spring Security remember me to your spring web application. Remember me is a convenient feature that allow user automatically logged to application without need to enter username and password.
Spring security provide two difference implement of remember me service Token-based remember me and Persistent remember me service
Today I just guide on implement of token based remember me.
1. How token-based remember me work
Token based remember me use user’s browser cookie to persistence one attribute composed as follows upon of successful interactive authentication:
Base64(username + ":" + expirationTime + ":" + md5Hex(username + ":" + expirationTime + ":" password + ":" + key)) password: That matches the one in the retrieved UserDetails expirationTime: The date and time when the remember-me token expires, expressed in milliseconds key: A private key to prevent modification of the remember-me token
when next time access Spring security will base on this cookie to get out
expirationTime. Then use
UserDetailsService to lookup password and build again md5hex to compare.
UserDetailsServicein your spring security configuration. If you have more than one
UserDetailsServiceyou must specific it.
2. Import project
We use source code of application from the post Spring security using JDBC authentication. You download the source code and import using eclipse by choose File->Import-> Existing Maven Projects
3. Login page
We change login page to add remember me check box.
.... <div class="form-group"> <label for="password">Password</label> <input id="c" type="password" class="form-control" required="required" name="password" placeholder="Password"> </div> <div class="form-group"> <input type="checkbox" name="_spring_security_remember_me"><span>Remember me</span> </div> <button type="submit" class="btn btn-default">Login</button> .....
4. Spring security configuration
We change spring security configuration file as below:
<security:http auto-config="true" use-expressions="true"> ..... <security:remember-me key="devjavkey" /> </security:http>
5. Run application
Supprise you do not need enter anything and you’ve already logged.
To look more detail we can use Chrome, open
Advance Setting, choose
Content setting and look on Cookie section, click on
All cookies and site data.... Then filter by
localhost you will see spring security cookie
6. Source code
You can download source code of this tutorial here