Spring Security Remember Me Example

In this lesson, we will see how to implement the Remember-me authentication so that our web application will be able to remember its users between sessions and allow them access without needing to log in every time.

In our case, we will use hashing to implement our remember-me strategy. In fact, a cookie is sent to the browser so that it will be detected in future sessions and causing auto login.


1. Technologies used

  • Spring Security 3.2.5.RELEASE
  • JSF 2.2.8
  • MySQL 5
  • Maven 3.0.5
  • Eclipse 4.5
  • JDK 1.7
  • Tomcat 7.0


2. Project structure



3. Database tables

We create table users:

Then we create table users_roles that contains user authorities

And we insert a user and his role:


4. Spring Security configuration

We start by enabling remember-me authentication by adding the <remember-me ../> element:

We create the  TokenBasedRememberMeServices implementation, it will retrieve the username and password from UserDetailsService in order to  generate the token that will be stored in the cookie and then shared with the RememberMeAuthenticationProvider using the key property.

Then we create the RememberMeAuthenticationProvider implementation that will process and validate the token generated by the rememberMeServices. It simply returns the same authentication object after making sure that the hash from the incoming request matches the stored one for the remember-me key

And we need to add the RememberMeAuthenticationFilter, it will see in the SecurityContext, if there is no user logged in, it will calls the RememberMeServices which will extract the “remember-me” cookie, decodes it, makes some validation and create an authentication object and then tries to authenticate this new authentication object against the RememberMeAuthenticationProvider using  the “remember me” token retrieved from the cookie.

We will use an authentication provider which use a UserDetailsService

In the <logout ../> element, we want that logout command invalidates the cookies, removing the remember-me information, and clearing the security context.

Here is the complete Spring Security configuration:

File : spring-security.xml


5. login page


We need to add the following element: <input name="_spring_security_remember_me" ../>


6. web.xml

When the application starts up, the rememberMeFilter will be in the filter chain of the server.


7. Test It

Go and visit the URL http://localhost:8080/SpringSecurityRememberMe/login.jsf

Check the remember-me option and log in.

SpringSecurityRememberMe 1

Log out and close the browser.

Then restart the application. Visit the URL http://localhost:8080/SpringSecurityRememberMe/welcome.jsf

We should be able to access the welcome page without logging in.

SpringSecurityRememberMe 2


Download source code

  • Keshav Sharma

    Without Login I Am Able To See Welcome Page