English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
基于表单的身份验证是一种通过登录表单完成用户身份验证的方式。该表单是内置的,由Spring security框架提供。
HttpSecurity类提供了formLogin()方法,该方法负责呈现登录表单并验证用户凭据。
在本教程中,我们将创建一个实现基于表单的身份验证的示例。让我们开始示例。
首先通过提供项目详细信息来创建Maven项目。
该项目最初看起来像这样:
通过使用以下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() // 로그인 양식을 렌더링합니다 .and() .logout() .logoutRequestMatcher(new AntPathRequestMatcher("/logout")); } }
HomeController라는 컨트롤러를 생성하고 다음에 넣습니다 com.w3codebox.controller 패키지에 포함되어 있습니다. 다음과 같은 코드가 포함되어 있습니다.
//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"; } }
이 프로젝트는 다음 두 개의 뷰(JSP 페이지)를 포함하고 있습니다. 그들을 다음에 넣으세요 WEB-INF/views 文件夹中。
//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>홈 페이지</title> </head> <body> <span style="color: green;">로그인 성공!</span> <a href="logout">Logout</a> <hr> <h3>환영하세요 관리자</h3> </body> </html>
//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> <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>
모든 이 파일을 추가한 후, 프로젝트 구조는 다음과 같습니다:
서버에서 애플리케이션을 실행한 후, 브라우저로 다음 출력이 생성됩니다.
출력:
링크를 클릭하면 양식 기반 인증을 위해 사용되는 로그인 양식이 표시됩니다.
그런 다음 인증 정보가 사용자 신원을 확인하고 관리 페이지로 표시됩니다.