Last updated: 2025-03-11
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 or React, 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
- Using the parameter name
"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(...)
. The rememberMe(...)
setup also adds its own RememberMeAuthenticationProvider
to the security config.
If we want to add the cookie automatically for every login, we can add a hidden input to our login form with our defined parameter name rememberMe
and the value true
. There is also the option to use .alwaysRemember(true)
at the config - however, this isn't working if our config also contains another security type like oauth2Login(...)
. For an optional cookie based on checkbox 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