Last updated: 2024-10-10
Adding remember-me authentication with Spring Boot
After we have set up a form-based login with Spring Boot and Thymeleaf, we want to add a remember-me option. Which steps are necessary so that the user receives a cookie when logging in and is automatically authenticated with it later on?
If you are looking for a remembered-me functionality for Angular, the article on Refresh Tokens in Spring Boot gives all the insights. As long as there is a valid refresh token, the user is automatically logged in on each visit.
Extension of our security config
As in the previous article, let's start by extending our security configuration. We can add our required setup in a new rememberMe(...)
section.
Adding remember-me support
In our example, we have configured the following aspects:
- Cookie duration of 180 days
- Reading the parameter
"rememberMe"
so that it corresponds with our login form - Use of the application property value of
"http.rememberMeKey"
for cookie encryption
The existing UserDetailsService
of our config is automatically integrated in the remember-me setup by Spring Boot. However, if there are several services available, we must specify it explicitly with .userDetailsService(...)
. If we have configured multiple AuthenticationManager
in our Spring Security setup, the manager of our current config should also integrate the RememberMeAuthenticationProvider
with our defined key for cookie encryption.
If we want to add the cookie automatically for every login, we can activate .alwaysRemember(true)
- then we can omit the rememberMeParameter(...)
setting and the following customization. Otherwise we extend our login form as follows.
Extension of our login form
A login request is always sent to the predefined Spring Security endpoint. Therefore, we now integrate a "rememberMe"
parameter into our form.
New option for our model class
We integrate the new field into our Thymeleaf form as follows.
New checkbox for our login form
If the user activates the new checkbox when logging in, a cookie "remember-me" is automatically created. After his session has expired, this cookie is found by Spring Security and the user is thus authenticated. If required, we could also customize the cookie name using the .rememberMeCookieName(...)
method.
With Bootify you can create a personalized Spring Boot application with your custom database schema and Thymeleaf frontend. In the Professional plan you can also configure a complex Spring Security setup including form-based login - with the options None
, Checkbox
or Always
for the remember-me cookie.
See Pricing
or read quickstart