Spring Security基于表单的认证

基于表单的认证是一种通过登录表单进行用户认证的方式。这个表单是由Spring Security框架内置并提供的。

HttpSecurity类提供了一个formLogin()方法,负责渲染登录表单并验证用户凭据。

在本教程中,我们将创建一个实现基于表单认证的示例。让我们开始这个例子。

spring-security-form-based-authentication.png
首先,创建一个Maven项目,提供项目详细信息。

项目初始状态如下:

spring-security-form-based-authentication2.png

Spring Security配置

在应用程序中配置Spring Security,使用以下Java文件。创建一个名为com.javatpoint的包,并将所有文件放入其中。

// AppConfig.java

package com.javatpoint;    
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.javatpoint.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.javatpoint;    
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.javatpoint;    
import org.springframework.security.web.context.*;    
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {    
    }    

// WebSecurityConfig.java

package com.javatpoint;  
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.javatpoint")    
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"));      
  }    
}    

控制器

创建一个名为HomeController的控制器,并将其放在com.javatpoint.controller包中。它包含以下代码。

// HomeController.java

package com.javatpoint.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";    
        }    
    }  

视图

此项目包含以下两个视图(JSP页面)。将它们放入WEB-INF/views文件夹中。

// index.jsp

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

// admin.jsp

<html>    
<head>    
<meta http-equiv="Content-Type" content="text/html; charset=UTF-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>   

项目依赖

// pom.xml

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.javatpoint</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>    
    <artifactId>javax.servlet-api</artifactId>    
    <version>3.1.0</version>    
    <scope>provided</scope>    
</dependency>    
<dependency>    
    <groupId>javax.servlet</groupId>    
    <artifactId>jstl</artifactId>    
    <version>1.2</version>    
</dependency>    
</dependencies>    
  <build>    
    <plugins>    
        <plugin>    
            <groupId>org.apache.maven.plugins</groupId>    
            <artifactId>maven-war-plugin</artifactId>    
            <version>2.6</version>    
            <configuration>    
                <failOnMissingWebXml>false</failOnMissingWebXml>    
            </configuration>    
        </plugin>    
    </plugins>    
</build>    
</project>  

项目结构

在添加了所有这些文件后,项目结构如下:

spring-security-form-based-authentication3.png

运行服务器

在服务器上运行应用程序,查看它在浏览器中的输出。

输出:

点击链接,将呈现一个登录表单,用于基于表单的认证。

spring-security-form-based-authentication4.png

在验证凭据后,它会对用户进行身份验证,并渲染到管理员页面。

spring-security-form-based-authentication5.png

spring-security-form-based-authentication6.png

标签: spring, Spring教程, Spring技术, Spring语言学习, Spring学习教程, Spring下载, Spring框架, Spring框架入门, Spring框架教程, Spring框架高级教程, Spring面试题, Spring笔试题, Spring编程思想