Spring Boot Security #3 | Remember Me persistent Token

Spring Boot Security #3 | Remember Me persistent Token

Persistent Token is the second way to get the remember functionality with Spring Boot Security. We will continue where we left the previous post. Spring-boot-security-remember-me-2.

We have an MVC project with Spring Boot + security where we put a cookie in session to use the “Remember-me” feature.

The problem is that this cookie contains a token with the user and the password and if someone intercepts this cookie I could log in and impersonate our identity.

The “solution” for this is to use a database to store the user, a value called “series”, the token and the last time it is used…

Also create a cookie in the browser but this is more complex. It will consist of “series” (random), and security token.

When the user tries to access the Web page The browser will detect the cookie and compare the value of “series”, token and username against the database and give access to the application.

Configuration

It is necessary to have the project worked like the previous post. SimpleRememberMe.

After getting the project and the necessary structure you must create a table in the database to maintain the persistence of the logins. The spring documentation has the structure of the table.

HTTPS://docs.spring.io/spring-security/site/docs/5.0.0.BUILD-SNAPSHOT/reference/htmlsingle/#remember-me-persistent-token


CREATE TABLE Persistent_logins (

Username varchar (50) NOT NULL,
series varchar (64) primary key
, varchar token (64) Not NUL
L, last_used timestamp not NU
LL);


In the file application.properties is necessary to include the following line to specify that the DataSource is managed by Hibernate.

Application properties with the specified data source

spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.springSessionContext


Code

At the code level you only have to modify the security configuration class. (WebSecurityConfig)

  1. ADD the data source variable with autowired annotation.
  2. Create the persistence method for the token repository.
  3. Clear cookie settings and add that persistence method to remember-me security
Security Configuration for Remember me token persist

Test

To test this method of “Remember-me” we will do it the way that with the previous method.

  1. Log in with the Remember Me box selected
  2. Verifies that the cookie in the browser exists
  3. Verifies that a record has been created in the persistence table
  4. Close the browser and open it again. Try to access a protected URL.
  5. Success?
  6. Log off and verify that the registry and cookie has been successfully removed from the database and browser.

Github repository:
https://github.com/cruizg93/SpringBoot-Security-MySql/tree/PersistentRememberMe

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *