Spring Security Custom Login

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

Spring Security Custom Login

Spring Security provides it's own built-in login module to authenticate the user. It validates the user credentials and provide accessibility into the application.

The login page rendered by the module is built-in. So, we does not require to create new jsp page. But if we want to customize the login page then how we can?

The answer is, we can create our own jsp login page and integrate to the application. In this topic we will create a custom login page and will use it to get login.

See, an example. Create a maven project by providing following details.

After finishing, it creates the following project structure.

Security Configuration

Configure project to apply spring security. It require following four files. Create a package com.javatpoint and put these files into this.

// AppConfig.java

  1. package comtpoint;  
  2.   
  3. import org.springframework.context.annotation.Bean;    
  4. import org.springframework.context.annotation.ComponentScan;    
  5. import org.springframework.context.annotation.Configuration;    
  6. import org.springframework.web.servlet.config.annotation.EnableWebMvc;    
  7. import org.springframework.web.servlet.view.InternalResourceViewResolver;    
  8. import org.springframework.web.servlet.view.JstlView;    
  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.     
  3. import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;    
  4. public class MvcWebApplicationInitializer extends    
  5.         AbstractAnnotationConfigDispatcherServletInitializer {    
  6.     @Override    
  7.     protected Class<?>[] getRootConfigClasses() {    
  8.         return new Class[] { WebSecurityConfig.class };    
  9.     }    
  10.     @Override    
  11.     protected Class<?>[] getServletConfigClasses() {    
  12.         // TODO Auto-generated method stub    
  13.         return null;    
  14.     }    
  15.     @Override    
  16.     protected String[] getServletMappings() {    
  17.         return new String[] { "/" };    
  18.     }    
  19. }  

// SecurityWebApplicationInitializer.java

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

// WebSecurityConfig.java

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

See, in configure method, after formLogin() a method loginPage("/login") is used. It is the actual method that required to call custom login page.

View

First create a login page our own. According to the spring official, the login page should looks like the below.

// login.jsp

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

// index.jsp

  1. <html>    
  2. <head>      
  3. <title>Home Page</title>    
  4. </head>    
  5. <body>    
  6. <h3> Welcome to hpnmaratt! <br> </h3>  
  7. <a href="admin">Login here</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. Login Successful!  
  8. <a href="logout">logout</a>    
  9. </body>    
  10. </html>   

Controller

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

// 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.         
  8.     @RequestMapping(value="/"method=RequestMethod.GET)    
  9.     public String index() {    
  10.             
  11.         return "index";    
  12.     }    
  13.     @RequestMapping(value="/login"method=RequestMethod.GET)    
  14.     public String login() {    
  15.             
  16.         return "login";    
  17.     }    
  18.     @RequestMapping(value="/admin"method=RequestMethod.GET)    
  19.     public String admin() {    
  20.             
  21.         return "admin";    
  22.     }    
  23. }    

Project 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>springcustomlogin</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

Our project looks like the this:

Run the Server

Output:

Now, login by providing user credentials.

See, it's working fine. Now, we can create it more decorative and custom according to the need.

Download this example.