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

基于Spring security表单的身份验证

基于表单的身份验证是一种通过登录表单完成用户身份验证的方式。该表单是内置的,由Spring security框架提供。

HttpSecurity类提供了formLogin()方法,该方法负责呈现登录表单并验证用户凭据。

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

创建Maven项目

首先通过提供项目详细信息来创建Maven项目。



该项目最初看起来像这样:



Spring Security配置

通过使用以下Java文件在应用程序中配置spring安全性。创建一个包 com.w3codebox 并将所有文件放入其中。

//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 {  
    }

//WebSecuiryConfig.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  
      
          
        @RequestMapping(value=\/\  
        public String index() {  
              
            return \  
        }  
        @RequestMapping(value=\/admin", method=RequestMethod.GET)  
        public String admin() {  
              
            return \  
        }  
    }

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! 


<a href="admin">Admin login</a>  
</body>  
</html>

//admin.jsp

<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
<title>Página Inicial</title>  
</head>  
<body>  
<span style="color: green;">autenticação bem-sucedida!</span>
<a href="logout">Sair</a>
<hr>
    <h3>Bem-vindo Admin</h3api  
</body>  
</html>

itens de dependência

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

Estrutura do Projeto

Após adicionar todos esses arquivos, a estrutura do projeto será como a seguinte:



Executar Servidor

Execute a aplicação no servidor e veja que ela gerará a seguinte saída para o navegador.

Saída:



Clique no link, será apresentado um formulário de login, que será usado para autenticação baseada em formulário.



Após a verificação das credenciais, a identidade do usuário será verificada e apresentada na página de administração.