Spring Security Form-Based Authentication

Spring Security Form-Based Authentication, 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 Form-Based Authentication

Spring Security Form-Based Authentication

Form-Based authentication is a way in which user's authentication is done by login form. This form is built-in and provided by spring security framework.

The HttpSecurity class provide a method formLogin() which is responsible to render login form and validate user credentials.

In this tutorial, we will create an example that implements form-based authentication. Lets start the example.

Create a Maven Project

First create a maven project by providing project details.

This project initially looks like this:

Spring Security Configuration

Configure spring security in the application by using the following Java files. Create a package com.javatpoint and put all the files into it.

// 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.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.point;    
  2. import org.springframework.security.web.context.*;    
  3. public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {    
  4.     }    

// WebSecuiryConfig.java

  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.tpoint")    
  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.   @Override    
  19.   protected void configure(HttpSecurity http) throws Exception {    
  20.       http.authorizeRequests().  
  21.       antMatchers("/index", "/user","/").permitAll()  
  22.       .antMatchers("/admin").authenticated()  
  23.       .and()  
  24.       .formLogin() // It renders a login form   
  25.       .and()  
  26.       .logout()  
  27.       .logoutRequestMatcher(new AntPathRequestMatcher("/logout"));      
  28.   }    
  29. }    

Controller

Create a controller HomeController and put inside the com.javatpoint.controller package. It contains the following code.

// HomeController.java

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

Views

This project contains the following two view (JSP pages). Put these into WEB-INF/views folder.

// index.jsp

  1. <html>    
  2. <head>      
  3. <title>Index Page</title>    
  4. </head>    
  5. <body>    
  6. Welcome to Samtpoint! <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. <span style="color: green;">login successful!</span>  
  8. <a href="logout">Logout</a>  
  9. <hr>  
  10.     <h3>Welcome Admin</h3>    
  11. </body>    
  12. </html>   

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>springsecurity</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 these files the project structure looks like this:

Run Server

Run the application over the server and see it produces the following output to the browser.

Output:

Click on link, a login form is rendered that will use for form-based authentication.

After validating credentials it authenticate the user and render to the admin page.