Spring security remember me

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 username and expirationTime. Then use UserDetailsService to lookup password and build again md5hex to compare.

**Note:  Remember me feature just can work if exist UserDetailsService in your spring security configuration. If you have more than one UserDetailsService you 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"
      <div class="form-group">
        <input type="checkbox" name="_spring_security_remember_me"><span>Remember me</span>
      <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" />

5. Run application

We run application, navigate to login pagetoken-based remember-me
We check Remember me and login, after success login we close broswer and open it again, navigator to home page http://localhost:8080/spring/home.do.

Supprise you do not need enter anything and you’ve already logged.

To look more detail we can use Chrome, open Setting, show 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 SPRING_SECURITY_REMEMBER_ME_COOKIE
spring security cookie

6. Source code

You can download source code of this tutorial here

Leave a Reply