Spring Security Login-Logout Module Example

Spring Security Login Logout, 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.

Spring Security Login-Logout Module Example

Spring Security Login-Logout Module Example

Spring Security provides login and logout features that we can use in our application. It is helpful to create secure Spring application.

Here, we are creating a Spring MVC application with Spring Security and implementing login and logout features.

First we created a maven project and provided following project dependencies in pom.xml file.

Project Dependencies

  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>springSecurityLoginOut</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.0.RELEASE</version>  
  26.     </dependency>  
  27.     <dependency>  
  28.         <groupId>org.springframework.security</groupId>  
  29.         <artifactId>spring-security-config</artifactId>  
  30.         <version>5.0.0.RELEASE</version>  
  31.     </dependency>  
  32.       
  33.         <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->  
  34. <dependency>  
  35.     <groupId>javax.servlet</groupId>  
  36.     <artifactId>javax.servlet-api</artifactId>  
  37.     <version>3.1.0</version>  
  38.     <scope>provided</scope>  
  39. </dependency>  
  40. <dependency>  
  41.     <groupId>javax.servlet</groupId>  
  42.     <artifactId>jstl</artifactId>  
  43.     <version>1.2</version>  
  44. </dependency>  
  45. </dependencies>  
  46.   <build>  
  47.     <plugins>  
  48.         <plugin>  
  49.             <groupId>org.apache.maven.plugins</groupId>  
  50.             <artifactId>maven-war-plugin</artifactId>  
  51.             <version>2.6</version>  
  52.             <configuration>  
  53.                 <failOnMissingWebXml>false</failOnMissingWebXml>  
  54.             </configuration>  
  55.         </plugin>  
  56.     </plugins>  
  57. </build>  
  58. </project>  

Spring Security Configuration

After that we created configuration files to enable login feature and allowed access to the authorized user only.

This project contains the following four Java files.

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.   
  9. @EnableWebMvc  
  10. @Configuration  
  11. @ComponentScan({ "com.javatpoint.controller.*" })  
  12. public class AppConfig {  
  13.     @Bean  
  14.     public InternalResourceViewResolver viewResolver() {  
  15.         InternalResourceViewResolver viewResolver  
  16.                           = new InternalResourceViewResolver();  
  17.         viewResolver.setViewClass(JstlView.class);  
  18.         viewResolver.setPrefix("/WEB-INF/views/");  
  19.         viewResolver.setSuffix(".jsp");  
  20.         return viewResolver;  
  21.     }  
  22. }  

MvcWebApplicationInitializer.java

  1. package com.tpoint;  
  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

  1. package com.tpoint;  
  2. import org.springframework.context.annotation.*;  
  3. //import org.springframework.security.config.annotation.authentication.builders.*;  
  4. import org.springframework.security.config.annotation.web.builders.HttpSecurity;  
  5. import org.springframework.security.config.annotation.web.configuration.*;  
  6. import org.springframework.security.core.userdetails.User;  
  7. import org.springframework.security.core.userdetails.UserDetailsService;  
  8. import org.springframework.security.provisioning.InMemoryUserDetailsManager;  
  9. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;  
  10. @EnableWebSecurity  
  11. @ComponentScan("com.javatpoint")  
  12. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {  
  13.       
  14.     @Bean  
  15.     public UserDetailsService userDetailsService() {  
  16.         InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();  
  17.         manager.createUser(User.withDefaultPasswordEncoder()  
  18.         .username("irfan").password("khan").roles("ADMIN").build());  
  19.         return manager;  
  20.     }  
  21.       
  22.     @Override  
  23.     protected void configure(HttpSecurity http) throws Exception {  
  24.                   
  25.         http                              
  26.         .authorizeRequests()  
  27.             .anyRequest().hasRole("ADMIN")  
  28.             .and().formLogin().and()  
  29.         .httpBasic()  
  30.         .and()  
  31.         .logout()  
  32.         .logoutUrl("/j_spring_security_logout")  
  33.         .logoutSuccessUrl("/")  
  34.         ;  
  35.     }  
  36. }  

Controller

HomeController: Controller to handle user requests.

  1. package com.tpoint.controller;  
  2. import javax.servlet.http.HttpServletRequest;  
  3. import javax.servlet.http.HttpServletResponse;  
  4. import org.springframework.security.core.Authentication;  
  5. import org.springframework.security.core.context.SecurityContextHolder;  
  6. import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;  
  7. import org.springframework.stereotype.Controller;  
  8. import org.springframework.web.bind.annotation.RequestMapping;  
  9. import org.springframework.web.bind.annotation.RequestMethod;  
  10. @Controller  
  11. public class HomeController {  
  12.     @RequestMapping(value = "/", method = RequestMethod.GET)  
  13.     public String index() {  
  14.         return "index";  
  15.     }  
  16.       
  17.     @RequestMapping(value="/logout", method=RequestMethod.GET)  
  18.     public String logoutPage(HttpServletRequest request, HttpServletResponse response) {  
  19.         Authentication auth = SecurityContextHolder.getContext().getAuthentication();  
  20.         if (auth != null){      
  21.            new SecurityContextLogoutHandler().logout(request, response, auth);  
  22.         }  
  23.          return "redirect:/";  
  24.      }  
  25. }  

Views

We have a JSP file index.jsp that contains the following code.

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3.     <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"   
  5. "http://www.w3.org/TR/html4/loose.dtd">  
  6. <html>  
  7. <head>  
  8. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  9. <title>Home</title>  
  10. </head>  
  11. <body>  
  12. <h3> Hello ${pageContext.request.userPrincipal.name}, </h3>  
  13. <h4>Welcome to hpnmaratt! </h4>  
  14. <a href="<c:url value='/logout' />">Click here to logout</a>  
  15. </body>  
  16. </html>  

Project Structure

After creating above files, our project structure looks like this:

Output

When run using apache tomcat, it produces the following output to the browser.

Now, providing user credentials to get logged in.

It shows home page after logged in successfully, see below.

Here, we are created a logout link which can be used to get logged out. Let's check out and log out from the application.

And it redirect back to the login page.

Well, we have created a successfully Spring MVC application that uses Spring Security to implement login and logout features.