基本身份验证

本节详细介绍了 Spring Security 如何为基于 Servlet 的应用程序提供 HTTP 基本身份验证支持。

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

basicauthenticationentrypoint
图 1. 发送 WWW-Authenticate 标头

上图基于我们的 SecurityFilterChain 图。

number 1 首先,用户对资源 /private 发出未经身份验证的请求,但该请求未经授权。

number 2 Spring Security 的 AuthorizationFilter 通过抛出 AccessDeniedException 来表示未经身份验证的请求被“拒绝”。

number 3 由于用户未通过身份验证,ExceptionTranslationFilter 启动“开始身份验证”。配置的 AuthenticationEntryPointBasicAuthenticationEntryPoint 的一个实例,它发送一个 WWW-Authenticate 标头。RequestCache 通常是一个 NullRequestCache,它不保存请求,因为客户端能够重播它最初请求的请求。

当请求带有 X-Requested-By: XMLHttpRequest 标头时,默认的 HTTP 基本身份验证提供程序将抑制 401 响应中的响应正文和 WWW-Authenticate 标头。这允许前端实现自己的身份验证代码,而不是触发浏览器登录对话框。要覆盖此行为,请实现您自己的 BasicAuthenticationEntryPoint

当客户端收到 WWW-Authenticate 标头时,它知道应该使用用户名和密码重试。下图显示了处理用户名和密码的流程

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

上图基于我们的 SecurityFilterChain 图。

number 1 当用户提交用户名和密码时,BasicAuthenticationFilter 通过从 HttpServletRequest 中提取用户名和密码来创建一个 UsernamePasswordAuthenticationToken,它是一种 Authentication 类型。

number 2 接下来,UsernamePasswordAuthenticationToken 被传递到 AuthenticationManager 进行身份验证。AuthenticationManager 的具体形式取决于 用户信息的存储方式

number 3 如果身份验证失败,则为“失败”。

  1. SecurityContextHolder 被清除。

  2. 调用 RememberMeServices.loginFail。如果未配置记住我功能,则此操作为空操作。请参阅 Javadoc 中的 RememberMeServices 接口。

  3. 调用 AuthenticationEntryPoint 以再次触发 WWW-Authenticate 的发送。请参阅 Javadoc 中的 AuthenticationEntryPoint 接口。

number 4 如果身份验证成功,则为“成功”。

默认情况下,Spring Security 的 HTTP 基本身份验证支持是启用的。但是,一旦提供了任何基于 Servlet 的配置,HTTP 基本身份验证必须明确提供。

以下示例显示了一个最小的、明确的配置

明确的 HTTP 基本配置
  • Java

  • XML

  • Kotlin

@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()
}
© . This site is unofficial and not affiliated with VMware.