基本身份验证
本节详细介绍了 Spring Security 如何为基于 Servlet 的应用程序提供 HTTP 基本身份验证支持。
本节描述了 HTTP 基本身份验证在 Spring Security 中的工作原理。首先,我们看到 WWW-Authenticate 标头被发送回未经身份验证的客户端
上图基于我们的 SecurityFilterChain 图。
首先,用户对资源 /private 发出未经身份验证的请求,但该请求未经授权。
Spring Security 的 AuthorizationFilter 通过抛出 AccessDeniedException 来表示未经身份验证的请求被“拒绝”。
由于用户未通过身份验证,ExceptionTranslationFilter 启动“开始身份验证”。配置的 AuthenticationEntryPoint 是 BasicAuthenticationEntryPoint 的一个实例,它发送一个 WWW-Authenticate 标头。RequestCache 通常是一个 NullRequestCache,它不保存请求,因为客户端能够重播它最初请求的请求。
|
当请求带有 |
当客户端收到 WWW-Authenticate 标头时,它知道应该使用用户名和密码重试。下图显示了处理用户名和密码的流程
上图基于我们的 SecurityFilterChain 图。
当用户提交用户名和密码时,BasicAuthenticationFilter 通过从 HttpServletRequest 中提取用户名和密码来创建一个 UsernamePasswordAuthenticationToken,它是一种 Authentication 类型。
接下来,UsernamePasswordAuthenticationToken 被传递到 AuthenticationManager 进行身份验证。AuthenticationManager 的具体形式取决于 用户信息的存储方式。
如果身份验证失败,则为“失败”。
-
调用
RememberMeServices.loginFail。如果未配置记住我功能,则此操作为空操作。请参阅 Javadoc 中的RememberMeServices接口。 -
调用
AuthenticationEntryPoint以再次触发 WWW-Authenticate 的发送。请参阅 Javadoc 中的AuthenticationEntryPoint接口。
如果身份验证成功,则为“成功”。
-
SecurityContextHolder中任何已通过身份验证的Authentication都将被加载,并且其权限将添加到返回的Authentication中。-
调用
RememberMeServices.loginSuccess。如果未配置记住我功能,则此操作为空操作。请参阅 Javadoc 中的RememberMeServices接口。 -
BasicAuthenticationFilter调用FilterChain.doFilter(request,response)以继续执行应用程序的其余逻辑。请参阅 Javadoc 中的BasicAuthenticationFilter类。
默认情况下,Spring Security 的 HTTP 基本身份验证支持是启用的。但是,一旦提供了任何基于 Servlet 的配置,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()
}