Spring Security - Basic Remember-Me Authentication using TokenBasedRememberMeServices

[Updated: Dec 6, 2017, Created: Dec 5, 2017]

Following example shows how to implement remember-me feature in web based authentication. Spring Security uses an implementation of RememberMeServices to provide the remember-me functionality.
There are two implementations of this interface: TokenBasedRememberMeServices (uses Base-64 encoded cookie, simple to use but not very secure) and PersistentTokenBasedRememberMeServices (persistent Token approach, uses a database table). Following example will show how to use first one i.e. TokenBasedRememberMeServices.


Java Config class

public class AppConfig extends WebSecurityConfigurerAdapter {

  protected void configure(HttpSecurity http) throws Exception {
          .tokenValiditySeconds(24 * 60 * 60);

  public void configure(AuthenticationManagerBuilder builder)
          throws Exception {

  public ViewResolver viewResolver() {
      InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
      return viewResolver;

By default rememberMe() will register TokenBasedRememberMeServices. If we don't provide cookie name and expiration in seconds then it will be initialized with cookie name 'remember-me' which will expire in two weeks (spring-security 5.0.0.RELEASE).


public class ExampleController {

  public String handleRequest(ModelMap map) {
      map.addAttribute("time", LocalDateTime.now().toString());
      return "my-page";

Post Login page


<html lang="en">
 <h2>Spring Security Example</h2>
 <p>Time: ${time}</p>
  <form action="/logout" method="post">
     <input type="hidden"
  <input type="submit" value="Logout">

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war


After authentication with remember-me checked, we can confirm the cookie in the browser. Following is from chrome:

Now even the current HTTP session expires, the server side will remember the logging information and will automatically login unless the cookie expires. Note that chrome is hard to expire session so it's difficult to test there, may be that's because it keeps the instances of the browser running in the background (check task manager in windows after closing Chrome). Test it with firefox or IE which invalidate the session as soon as we close the browser.

Example Project

Dependencies and Technologies Used :

  • spring-security-web 5.0.0.RELEASE: spring-security-web.
  • spring-security-config 5.0.0.RELEASE: spring-security-config.
  • spring-webmvc 4.3.9.RELEASE: Spring Web MVC.
  • javax.servlet-api 3.1.0 Java Servlet API
  • JDK 1.8
  • Maven 3.3.9

Remember-me example with TokenBasedRememberMeServices Select All Download
  • remember-me-basic-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • webapp
          • WEB-INF
            • views

See Also