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

基本身份验证

本节详细介绍了 Spring Security 如何为基于 servlet 的应用程序提供对基本 HTTP 身份验证的支持。spring-doc.cadn.net.cn

本节描述了 HTTP 基本身份验证在 Spring Security 中的工作原理。 首先,我们看到 WWW-Authenticate 标头被发送回未经身份验证的客户端:spring-doc.cadn.net.cn

BasicAuthenticationEntryPoint
图 1.发送 WWW-Authenticate 报头

前面的图建立在我们的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。 配置的AuthenticationEntryPointBasicAuthenticationEntryPoint,它发送 WWW-Authenticate 标头。 这RequestCache通常是NullRequestCache这不会保存请求,因为 Client 端能够重放它最初请求的请求。spring-doc.cadn.net.cn

当客户端收到WWW-Authenticate标头,它知道它应该使用用户名和密码重试。 下图显示了正在处理的用户名和密码的流程:spring-doc.cadn.net.cn

basicauthenticationfilter
图 2.验证用户名和密码

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

数字 1当用户提交其用户名和密码时,BasicAuthenticationFilter创建一个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. AuthenticationEntryPoint以触发 WWW-Authenticate 再次发送。 请参阅AuthenticationEntryPoint接口。spring-doc.cadn.net.cn

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

  1. AuthenticationSecurityContextHolder上设置。spring-doc.cadn.net.cn

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

  3. BasicAuthenticationFilter调用FilterChain.doFilter(request,response)以继续执行 Application Logic 的其余部分。 请参阅BasicAuthenticationFilterJavadoc 中的 Classspring-doc.cadn.net.cn

默认情况下,Spring Security 的 HTTP 基本身份验证支持处于启用状态。 但是,一旦提供了任何基于 servlet 的配置,就必须显式提供 HTTP Basic。spring-doc.cadn.net.cn

以下示例显示了一个最小的显式配置:spring-doc.cadn.net.cn

显式 HTTP 基本配置
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) {
	http
		// ...
		.httpBasic(withDefaults());
	return http.build();
}
<http>
	<!-- ... -->
	<http-basic />
</http>
@Bean
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
	http {
		// ...
		httpBasic { }
	}
	return http.build()
}