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.

Example

Java Config class

@Configuration
@EnableWebSecurity
@EnableWebMvc
@ComponentScan
public class AppConfig extends WebSecurityConfigurerAdapter {

  protected void configure(HttpSecurity http) throws Exception {
      http.authorizeRequests()
          .anyRequest().authenticated()
          .and()
          .formLogin()
          .and()
          .rememberMe()
          .rememberMeCookieName("example-app-remember-me")
          .tokenValiditySeconds(24 * 60 * 60);
  }

  @Override
  public void configure(AuthenticationManagerBuilder builder)
          throws Exception {
      builder.inMemoryAuthentication()
             .withUser("joe")
             .password("123")
             .roles("ADMIN");
  }

  @Bean
  public ViewResolver viewResolver() {
      InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
      viewResolver.setPrefix("/WEB-INF/views/");
      viewResolver.setSuffix(".jsp");
      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).

Controller

@Controller
public class ExampleController {

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

Post Login page

src/main/webapp/WEB-INF/views/my-page.jsp

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

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

mvn tomcat7:run-war

Output

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