此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Security 6.4.1spring-doc.cadn.net.cn

表单登录

Spring Security 支持通过 HTML 表单提供用户名和密码。 本节详细介绍了基于表单的身份验证在 Spring Security 中的工作原理。spring-doc.cadn.net.cn

本节介绍基于表单的登录在 Spring Security 中的工作原理。 首先,我们了解用户是如何被重定向到登录表单的:spring-doc.cadn.net.cn

loginurlauthentication入口点
图 1.重定向到登录页面

前面的图建立在我们的SecurityFilterChain图。spring-doc.cadn.net.cn

数字 1首先,用户向资源发出未经身份验证的请求 (/private),但未获得授权。spring-doc.cadn.net.cn

编号 2Spring Security 的AuthorizationFilter表示未经身份验证的请求被拒绝,方法是抛出AccessDeniedException.spring-doc.cadn.net.cn

编号 3由于用户未经过身份验证,因此ExceptionTranslationFilter启动 Start Authentication 并将重定向发送到具有已配置AuthenticationEntryPoint. 在大多数情况下,AuthenticationEntryPointLoginUrlAuthenticationEntryPoint.spring-doc.cadn.net.cn

编号 4浏览器请求它重定向到的登录页面。spring-doc.cadn.net.cn

号码 5应用程序中的某些内容必须呈现登录页面spring-doc.cadn.net.cn

提交用户名和密码后,UsernamePasswordAuthenticationFilter验证用户名和密码。 这UsernamePasswordAuthenticationFilter扩展了AbstractAuthenticationProcessingFilter,因此下图应该看起来非常相似:spring-doc.cadn.net.cn

用户名密码身份验证过滤器
图 2.验证用户名和密码

该图建立在我们的SecurityFilterChain图。spring-doc.cadn.net.cn

数字 1当用户提交其用户名和密码时,UsernamePasswordAuthenticationFilter创建一个UsernamePasswordAuthenticationToken,这是一种Authentication,方法是从HttpServletRequest实例。spring-doc.cadn.net.cn

编号 2接下来,UsernamePasswordAuthenticationToken传递到AuthenticationManager实例进行身份验证。 什么的细节AuthenticationManager看起来取决于用户信息的存储方式。spring-doc.cadn.net.cn

编号 3如果身份验证失败,则为 Failurespring-doc.cadn.net.cn

  1. SecurityContextHolder被清除。spring-doc.cadn.net.cn

  2. RememberMeServices.loginFail被调用。 如果未配置 Remember me,则为 no-op。 请参阅RememberMeServices接口。spring-doc.cadn.net.cn

  3. AuthenticationFailureHandler被调用。 请参阅AuthenticationFailureHandlerjavadoc 中的 classspring-doc.cadn.net.cn

编号 4如果身份验证成功,则为 Successspring-doc.cadn.net.cn

  1. SessionAuthenticationStrategy收到新登录的通知。 请参阅SessionAuthenticationStrategy接口。spring-doc.cadn.net.cn

  2. AuthenticationSecurityContextHolder上设置。 请参阅SecurityContextPersistenceFilter类。spring-doc.cadn.net.cn

  3. RememberMeServices.loginSuccess被调用。 如果未配置 Remember me,则为 no-op。 请参阅RememberMeServices接口。spring-doc.cadn.net.cn

  4. ApplicationEventPublisher发布InteractiveAuthenticationSuccessEvent.spring-doc.cadn.net.cn

  5. AuthenticationSuccessHandler被调用。通常,这是一个SimpleUrlAuthenticationSuccessHandler,该请求会重定向到由ExceptionTranslationFilter当我们重定向到登录页面时。spring-doc.cadn.net.cn

默认情况下,Spring Security 表单登录处于启用状态。 但是,一旦提供了任何基于 servlet 的配置,就必须显式提供基于表单的登录。 以下示例显示了一个最小的显式 Java 配置:spring-doc.cadn.net.cn

表单登录
public SecurityFilterChain filterChain(HttpSecurity http) {
	http
		.formLogin(withDefaults());
	// ...
}
<http>
	<!-- ... -->
	<form-login />
</http>
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
	http {
		formLogin { }
	}
	// ...
}

在前面的配置中, Spring Security 呈现默认登录页面。 大多数生产应用程序都需要自定义登录表单。spring-doc.cadn.net.cn

以下配置演示了如何提供自定义登录表单。spring-doc.cadn.net.cn

自定义登录表单配置
public SecurityFilterChain filterChain(HttpSecurity http) {
	http
		.formLogin(form -> form
			.loginPage("/login")
			.permitAll()
		);
	// ...
}
<http>
	<!-- ... -->
	<intercept-url pattern="/login" access="permitAll" />
	<form-login login-page="/login" />
</http>
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
	http {
		formLogin {
			loginPage = "/login"
			permitAll()
		}
	}
	// ...
}

在 Spring Security 配置中指定登录页面时,您负责呈现该页面。 以下 Thymeleaf 模板生成一个 HTML 登录表单,该表单符合/login.:spring-doc.cadn.net.cn

登录表单 - src/main/resources/templates/login.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org">
	<head>
		<title>Please Log In</title>
	</head>
	<body>
		<h1>Please Log In</h1>
		<div th:if="${param.error}">
			Invalid username and password.</div>
		<div th:if="${param.logout}">
			You have been logged out.</div>
		<form th:action="@{/login}" method="post">
			<div>
			<input type="text" name="username" placeholder="Username"/>
			</div>
			<div>
			<input type="password" name="password" placeholder="Password"/>
			</div>
			<input type="submit" value="Log in" />
		</form>
	</body>
</html>

关于默认 HTML 表单,有几个关键点:spring-doc.cadn.net.cn

许多用户只需要自定义登录页面即可。 但是,如果需要,您可以使用其他配置自定义前面显示的所有内容。spring-doc.cadn.net.cn

如果使用 Spring MVC,则需要一个控制器,该控制器将GET /login添加到我们创建的登录模板中。 以下示例显示了一个最小值LoginController:spring-doc.cadn.net.cn

LoginController 控制器
@Controller
class LoginController {
	@GetMapping("/login")
	String login() {
		return "login";
	}
}
@Controller
class LoginController {
    @GetMapping("/login")
    fun login(): String {
        return "login"
    }
}