English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Form-based authentication based on Spring security

Form-based authentication is a way to complete user authentication through a login form. The form is built-in and provided by the Spring security framework.

The HttpSecurity class provides the formLogin() method, which is responsible for displaying the login form and verifying user credentials.

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

Create Maven Project

First, create a Maven project by providing project details.



The project initially looks like this:



Spring Security Configuration

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

//AppConfig.java

package com.w3codebox;  
import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.ComponentScan;  
import org.springframework.context.annotation.Configuration;  
import org.springframework.web.servlet.config.annotation.EnableWebMvc;  
import org.springframework.web.servlet.view.InternalResourceViewResolver;  
import org.springframework.web.servlet.view.JstlView;  
@EnableWebMvc  
@Configuration  
@ComponentScan({ "com.w3codebox.controller.*" })  
public class AppConfig {  
    @Bean  
    public InternalResourceViewResolver viewResolver() {  
        InternalResourceViewResolver viewResolver  
                          = new InternalResourceViewResolver();  
        //viewResolver.setViewClass(JstlView.class);  
        viewResolver.setPrefix("/WEB-INF/views/");  
        viewResolver.setSuffix(".jsp");  
        return viewResolver;  
    }  
}

//MvcWebApplicationInitializer.java

package com.w3codebox;  
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;  
public class MvcWebApplicationInitializer extends  
        AbstractAnnotationConfigDispatcherServletInitializer {  
    @Override  
    protected Class<?>[] getRootConfigClasses() {  
        return new Class[] { WebSecurityConfig.class };  
    }  
    @Override  
    protected Class<?>[] getServletConfigClasses() {  
        // TOdo Auto-generated method stub  
        return null;  
    } 
    @Override  
    protected String[] getServletMappings() {  
        return new String[] { "/" };  
    }  
}

//SecurityWebApplicationInitializer.java

package com.w3codebox;  
import org.springframework.security.web.context.*;  
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {  
    }

//WebSecurityConfig.java

package com.w3codebox;
import org.springframework.context.annotation.*;    
import org.springframework.security.config.annotation.web.builders.HttpSecurity;  
import org.springframework.security.config.annotation.web.configuration.*;  
import org.springframework.security.core.userdetails.*;  
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;  
@EnableWebSecurity  
@ComponentScan("com.w3codebox)  
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {  
  @Bean  
  public UserDetailsService userDetailsService() {  
      InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();  
      manager.createUser(User.withDefaultPasswordEncoder()
      .username("admin").password("admin123).roles("ADMIN").build());  
      return manager;  
  }  
  @Override  
  protected void configure(HttpSecurity http) throws Exception {}}  
      http.authorizeRequests().
      antMatchers("/index", "/user","/").permitAll()
      .antMatchers("/admin()).authenticated()
      .and()
      .formLogin() // It renders a login form 
      .and()
      .logout()
      .logoutRequestMatcher(new AntPathRequestMatcher("/logout");     
  }  
}

controller

Create a controller HomeController and place it in com.w3codebox.controller package. It contains the following code.

//HomeController.java

package com.w3codebox.controller;  
    import org.springframework.stereotype.Controller;  
    import org.springframework.web.bind.annotation.RequestMapping;  
    import org.springframework.web.bind.annotation.RequestMethod;  
    
    @Controller  
    public class HomeController {  
          
        @RequestMapping(value="/", method=RequestMethod.GET)  
        public String index() {  
              
            return "index";  
        }  
        @RequestMapping(value="/admin", method=RequestMethod.GET)  
        public String admin() {  
              
            return "admin";  
        }  
    }

views

This project includes the following two views (JSP pages). Place them in WEB-INF/views folder.

//index.jsp

<html>  
<head>    
<title>Index Page</title>  
</head>  
<body>  
Welcome to w3codebox!  <br>  <br>
<a href="admin">Admin login</a>  
</body>  
</html>

//admin.jsp

<html>  
<head>  
<meta http-equiv="Content-Type-equiv="Content-Type-Type" content="text/html/html; charset=UTF-8-8">  
<title>Home Page</title>  
</head>  
<body>  
<span style="color: green;">login successful!</span>
<a href="logout">Logout</a>
<hr>
    <h3>Welcome Admin</h3>  
</body>  
</html>

Project Dependencies

//pom.xml

<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">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.w3codebox</groupId>
  <artifactId>springsecurity</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <properties>  
    <maven.compiler.target>1.8</maven.compiler.target>  
    <maven.compiler.source>1.8</maven.compiler.source>  
</properties>  
<dependencies>  
  <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-webmvc</artifactId>  
            <version>5.0.2.RELEASE</version>  
        </dependency>  
        <dependency>  
        <groupId>org.springframework.security</groupId>  
        <artifactId>spring-security-web</artifactId>  
        <version>5.0.0.RELEASE</version>  
    </dependency>  
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-core</artifactId>
    <version>5.0.4.RELEASE</version>
</dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-config -->
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>5.0.4.RELEASE</version>
</dependency>
    
      
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->  
<dependency>  
    <groupId>javax.servlet</groupId>/groupId>  
    <artifactId>javax.servlet-api</artifactId>-api/artifactId>  
    <version>3.1.0/version>  
    <scope>provided</scope>/scope>  
</dependency>  
<dependency>  
    <groupId>javax.servlet</groupId>/groupId>  
    <artifactId>jstl</artifactId>/artifactId>  
    <version>1.2</version>  
</dependency>  
</dependencies>  
  <build>  
    <plugins>  
        <plugin>  
            <groupId>org.apache.maven.plugins</groupId>/groupId>  
            <artifactId>maven-war-plugin/artifactId>  
            <version>2.6</version>  
            <configuration>  
                <failOnMissingWebXml>false</failOnMissingWebXml>/failOnMissingWebXml>  
            </configuration>  
        </plugin>  
    </plugins>  
</build>  
</project>

Project Structure

After adding all these files, the project structure will be as follows:



Run the Server

Run the application on the server and then see that it generates the following output to the browser.

Output:



Click the link to display a login form that will be used for form-based authentication.



After verification, credentials will verify the user's identity and present the admin page.