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.
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)
- ADD the data source variable with autowired annotation.
- Create the persistence method for the token repository.
- Clear cookie settings and add that persistence method to remember-me security
Test
To test this method of “Remember-me” we will do it the way that with the previous method.
- Log in with the Remember Me box selected
- Verifies that the cookie in the browser exists
- Verifies that a record has been created in the persistence table
- Close the browser and open it again. Try to access a protected URL.
- Success?
- 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