How to configure Persistent Token Remember-Me authentication

Remember-me authentication is a solution for websites to remember the identity of a user between sessions. In the tutorial, JavaSampleApppoach will show you how to configure persistent token remember-me authentication with Spring Boot.

Related Articles:
How to configure Remember Me authentication by Hash-Based Token Approach
Spring Security – Config Security for Web MVC by Spring Boot


I. Technologies

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Spring Boot: 1.5.1.RELEASE
– MySQL database

II. Practices – Persistent Token Remember-Me authentication

Step to do
– Create SpringBoot project
– Create Controller & Views
– Setup MySql database configuration

– Configure remember-me security

– Run & Check results

1. Create SpringBoot project

Open Spring Tool Suite, on main menu, choose File->New->Spring Starter Project, add project info, then press Next for needed dependencies:
– For Security, choose Core->Security
– For JDBC & MySQL, choose SQL->JDBC & MySQL
– For Template Engines, choose Thymeleaf
– For Web MVC, choose Web->Web

springboot remember me Persistent approach

Open pom.xml, check dependencies:


	org.springframework.boot
	spring-boot-starter-security


	org.springframework.boot
	spring-boot-starter-thymeleaf


	org.springframework.boot
	spring-boot-starter-web



	org.springframework.boot
	spring-boot-starter-jdbc



	mysql
	mysql-connector-java

2. Create Controller & Views

– Create a simple controller WebController:

package com.javasampleapproach.rememberme.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class WebController {

	@RequestMapping(value = { "/"})
	public String home() {
		return "home";
	}

	@RequestMapping(value = { "/login" })
	public String login() {
		return "login";
	}
}

– Create 2 views:

home.html



 
 Security with Spring Boot
 
 
     

Hello! Welcome to Remember-me authentication by Persistent Token Approach!

%MINIFYHTMLe6011e763a9c807247505260ea50c00814%

login.html with Remember me checkbox:



 
 Remember Me!
 
 
     

Username or Password is wrong! Please check again

Logged out.

Username:
Password:
Remember Me:
3. Setup MySql database configurations

Open application.properties file, configure datasource:

spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=12345

On MySQL database: testbdb, create persistent_logins table by below script:

create table persistent_logins (
	username varchar(64) not null, 
	series varchar(64) primary key, 	
	token varchar(64) not null,
	last_used timestamp not null
)
4. Configure remember-me security

Configure datasource for remember-me.

Full Sourcecode

package com.javasampleapproach.rememberme.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	
	@Autowired
	DataSource dataSource;
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().anyRequest().authenticated()
						.and()
							.formLogin()
								.loginPage("/login")
								.permitAll()
						.and()
							.rememberMe()
								.rememberMeCookieName("javasampleapproach-remember-me")
								.tokenValiditySeconds(24 * 60 * 60) // expired time = 1 day
								.tokenRepository(persistentTokenRepository())
						.and()
							.logout()
							.permitAll();
	}

	@Bean
	public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
        tokenRepository.setDataSource(dataSource);
        return tokenRepository;
    }
	
	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
		auth.inMemoryAuthentication().withUser("user").password("user").roles("USER");
	}	
}
5. Run & Check results

Build & Run the project with SpringBoot App mode.

5.1 Check with normal cookie

– Make the firstly request: http://localhost:8080 -> login page will be redicted immediately, use account: user/user for authentication, But NOT check Remember me.
=> Result: Login successfully, having 1 cookie: JSESSIONID. No record in persistent_logins table

springboot remember me Persistent approach - jsessionid

– Delete JSESSIONID and make above request again: http://localhost:8080 => login page will be re-direct immediately for authentication again.

5.2 Check with Remember-me cookie

– Login with account: user/user, But check Remember me
>>> Authentication successfully. Having 2 cookies: JSESSIOINID & javasampleapproach-remember-me:

Spring boot Persistent Token Remember-Me authentication

javasampleapproach-remember-me cookie has 1 day for expired time.

>>> And 1 record in persistent_logins table:

springboot Persistent token remember-me approach - record in persistent_logins

– Remove JSESSIONID cookie, then make the request: http://localhost:8080
-> NOT redirect to login page (because having javasampleapproach-remember-me cookie)

– Remove JSESSIONID & javasampleapproach-remember-me cookie, then make the request: http://localhost:8080, login page will be redirect >>> Right!

It works fine!

III. SourceCode

SpringLoginRememberMe



By grokonez | April 17, 2017.

Last updated on August 8, 2017.



Related Posts


2 thoughts on “How to configure Persistent Token Remember-Me authentication”

  1. Hei can you explain me “tokenValiditySeconds”. Every time after deploy my site, i got some user logged out.

Got Something To Say:

Your email address will not be published. Required fields are marked *

*