Spring Security Remember Me

Spring Security Remember Me, Introduction, Features, Project Modules, XML Example, Java Example, Login Logout, Spring Boot, Spring Core, Spring with JPA, Spring with Hibernate, Spring with Struts, Spring MVC, Spring Integration etc.

 0
Spring Security Remember Me

Spring Security Remember Me

Remember me is a feature that allows a user to access into application without re-login. User's login session terminates after closing the browser and if user again access the application by opening browser, it prompts for login.

But we can avoid this re-login by using remember me feature. It stores user's identity into the Cookie or database and use to identity the user.

We are implementing this into the following example. Lets see an example.

Create a Maven Project

First create a maven project and provide the project details.

Initially, project looks like this:

Spring Security Configuration

Configure the project to implement spring security. It requires following four Java files. First create a package com.javatpoint and put all the files into this.

// AppConfig.java

  1. package com.tpoint;  
  2. import org.springframework.context.annotation.Bean;    
  3. import org.springframework.context.annotation.ComponentScan;    
  4. import org.springframework.context.annotation.Configuration;    
  5. import org.springframework.web.servlet.config.annotation.EnableWebMvc;    
  6. import org.springframework.web.servlet.view.InternalResourceViewResolver;    
  7. import org.springframework.web.servlet.view.JstlView;    
  8. @EnableWebMvc    
  9. @Configuration    
  10. @ComponentScan({ "com.javatpoint.controller.*" })    
  11. public class AppConfig {    
  12.     @Bean    
  13.     public InternalResourceViewResolver viewResolver() {    
  14.         InternalResourceViewResolver viewResolver    
  15.                           = new InternalResourceViewResolver();    
  16.         viewResolver.setViewClass(JstlView.class);    
  17.         viewResolver.setPrefix("/WEB-INF/views/");    
  18.         viewResolver.setSuffix(".jsp");    
  19.         return viewResolver;    
  20.     }    
  21. }   

// MvcWebApplicationInitializer.java

  1. package com.point;    
  2. import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;    
  3. public class MvcWebApplicationInitializer extends    
  4.         AbstractAnnotationConfigDispatcherServletInitializer {    
  5.     @Override    
  6.     protected Class<?>[] getRootConfigClasses() {    
  7.         return new Class[] { WebSecurityConfig.class };    
  8.     }    
  9.     @Override    
  10.     protected Class<?>[] getServletConfigClasses() {    
  11.         // TODO Auto-generated method stub    
  12.         return null;    
  13.     }    
  14.     @Override    
  15.     protected String[] getServletMappings() {    
  16.         return new String[] { "/" };    
  17.     }    
  18. }  

// SecurityWebApplicationInitializer.java

  1. package com.tpoint;    
  2. import org.springframework.security.web.context.*;          
  3.     public class SecurityWebApplicationInitializer    
  4.         extends AbstractSecurityWebApplicationInitializer {    
  5.     }  

// WebSecurityConfig.java

In this class, we are creating user and authenticating as well. The rememberMe() method inside the configure() method is responsible to remember and store user identity.

  1. package com.tpoint;  
  2. import org.springframework.context.annotation.*;      
  3. import org.springframework.security.config.annotation.web.builders.HttpSecurity;    
  4. import org.springframework.security.config.annotation.web.configuration.*;    
  5. import org.springframework.security.core.userdetails.*;    
  6. import org.springframework.security.provisioning.InMemoryUserDetailsManager;  
  7. import org.springframework.security.web.util.matcher.AntPathRequestMatcher;    
  8. @EnableWebSecurity    
  9. @ComponentScan("com.javatpoint")    
  10. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {    
  11. @Bean    
  12. public UserDetailsService userDetailsService() {    
  13.     InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();    
  14.     manager.createUser(User.withDefaultPasswordEncoder()  
  15.     .username("admin").password("admin123").roles("ADMIN").build());    
  16.     return manager;    
  17. }    
  18.     
  19. @Override    
  20. protected void configure(HttpSecurity http) throws Exception {    
  21.       
  22.       http.authorizeRequests().  
  23.       antMatchers("/index", "/user","/").permitAll()  
  24.       .antMatchers("/admin").authenticated()  
  25.       .and()  
  26.       .formLogin()  
  27.       .loginPage("/login")  
  28.       .and()  
  29.       .rememberMe()  
  30.       .key("rem-me-key")  
  31.       .rememberMeParameter("remember") // it is name of checkbox at login page  
  32.       .rememberMeCookieName("rememberlogin") // it is name of the cookie  
  33.       .tokenValiditySeconds(100) // remember for number of seconds  
  34.       .and()  
  35.       .logout()  
  36.       .logoutRequestMatcher(new AntPathRequestMatcher("/logout"));    
  37. }    
  38. }  

Controller

Create a controller HomeController inside the com.javatpoint.controller package. See the controller code.

// HomeController.java

  1. package com.tpoint.controller;  
  2. import org.springframework.stereotype.Controller;  
  3. import org.springframework.web.bind.annotation.RequestMapping;  
  4. import org.springframework.web.bind.annotation.RequestMethod;  
  5. @Controller  
  6. public class HomeController {  
  7.     @RequestMapping(value = "/"method = RequestMethod.GET)  
  8.     public String index() {  
  9.         return "index";  
  10.     }  
  11.     @RequestMapping(value = "/login"method = RequestMethod.GET)  
  12.     public String login() {  
  13.         return "login";  
  14.     }  
  15.     @RequestMapping(value = "/admin"method = RequestMethod.GET)  
  16.     public String admin() {  
  17.         return "admin";  
  18.     }  
  19.  

View

Create view (JSP pages) to produce output to the browser.

// index.jsp

  1. <html>    
  2. <head>      
  3. <title>Home Page</title>    
  4. </head>    
  5. <body>    
  6. Welcome to hpnmaratt! <br> <br>  
  7. <a href="admin">Admin login</a>    
  8. </body>    
  9. </html>  

// admin.jsp

  1. <html>    
  2. <head>    
  3. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">    
  4. <title>Home Page</title>    
  5. </head>    
  6. <body>    
  7. Welcome Admin! ?  
  8. <a href="logout">logout</a>    
  9. </body>    
  10. </html>    

// login.jsp

This is our custom login page in which we added remember me check box. See the code.

  1. <%@ taglib  
  2.     prefix="c"  
  3.     uri="http://java.sun.com/jsp/jstl/core"   
  4. %>  
  5. <c:url value="/login" var="loginUrl"/>  
  6. <form action="${loginUrl}" method="post">         
  7.     <c:if test="${param.error != null}">          
  8.         <p>  
  9.             Invalid username and password.  
  10.         </p>  
  11.     </c:if>  
  12.     <c:if test="${param.logout != null}">         
  13.         <p>  
  14.             You have been logged out.  
  15.         </p>  
  16.     </c:if>  
  17.     <p>  
  18.         <label for="username">Username</label>  
  19.         <input type="text" id="username" name="username"/>      
  20.     </p>  
  21.     <p>  
  22.         <label for="password">Password</label>  
  23.         <input type="password" id="password" name="password"/>      
  24.     </p>  
  25.     <p>  
  26.         <label for="remember"> Remember me</label>  
  27.         <input type="checkbox" name="remember" />  
  28.     </p>  
  29.     <input type="hidden"                          
  30.         name="${_csrf.parameterName}"  
  31.         value="${_csrf.token}"/>  
  32.     <button type="submit" class="btn">Log in</button>  
  33. </form>  

Project Dependencies

Following is our pom.xml file that contains all required dependencies.

// pom.xml

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
  2.   <modelVersion>4.0.0</modelVersion>  
  3.   <groupId>com.javatpoint</groupId>  
  4.   <artifactId>springrememberme</artifactId>  
  5.   <version>0.0.1-SNAPSHOT</version>  
  6.   <packaging>war</packaging>  
  7.   <properties>    
  8.     <maven.compiler.target>1.8</maven.compiler.target>    
  9.     <maven.compiler.source>1.8</maven.compiler.source>    
  10. </properties>    
  11. <dependencies>    
  12.   <dependency>    
  13.             <groupId>org.springframework</groupId>    
  14.             <artifactId>spring-webmvc</artifactId>    
  15.             <version>5.0.2.RELEASE</version>    
  16.         </dependency>    
  17.         <dependency>    
  18.         <groupId>org.springframework.security</groupId>    
  19.         <artifactId>spring-security-web</artifactId>    
  20.         <version>5.0.0.RELEASE</version>    
  21.     </dependency>    
  22. <dependency>  
  23.     <groupId>org.springframework.security</groupId>  
  24.     <artifactId>spring-security-core</artifactId>  
  25.     <version>5.0.4.RELEASE</version>  
  26. </dependency>  
  27.     <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-config -->  
  28. <dependency>  
  29.     <groupId>org.springframework.security</groupId>  
  30.     <artifactId>spring-security-config</artifactId>  
  31.     <version>5.0.4.RELEASE</version>  
  32. </dependency>  
  33.       
  34.         
  35.         <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->    
  36. <dependency>    
  37.     <groupId>javax.servlet</groupId>    
  38.     <artifactId>javax.servlet-api</artifactId>    
  39.     <version>3.1.0</version>    
  40.     <scope>provided</scope>    
  41. </dependency>    
  42. <dependency>    
  43.     <groupId>javax.servlet</groupId>    
  44.     <artifactId>jstl</artifactId>    
  45.     <version>1.2</version>    
  46. </dependency>    
  47. </dependencies>    
  48.   <build>    
  49.     <plugins>    
  50.         <plugin>    
  51.             <groupId>org.apache.maven.plugins</groupId>    
  52.             <artifactId>maven-war-plugin</artifactId>    
  53.             <version>2.6</version>    
  54.             <configuration>    
  55.                 <failOnMissingWebXml>false</failOnMissingWebXml>    
  56.             </configuration>    
  57.         </plugin>    
  58.     </plugins>    
  59. </build>    
  60. </project>  

Project Structure

After adding all the files the project structure looks like this:

Run Server

Output:

Click on Admin login link and login.

See, we have clicked on remember me check box.

Copy the URL: http://localhost:8080/springrememberme/admin and close the browser completely. After a second open browser and paste the copied URL.

See, it does not ask for login and land us on the same page. Because we did check remember me button during login.