基本认证
本节详细介绍了 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被调用。如果未配置“记住我”,则这是一个空操作。请参阅 API 文档中的RememberMeServices接口。 -
AuthenticationEntryPoint被调用以触发 WWW-Authenticate 再次发送。请参阅 API 文档中的AuthenticationEntryPoint接口。
如果认证成功,则为 成功。
-
Authentication 被设置在 SecurityContextHolder 上。
-
RememberMeServices.loginSuccess被调用。如果未配置“记住我”,则这是一个空操作。请参阅 API 文档中的RememberMeServices接口。 -
BasicAuthenticationFilter调用FilterChain.doFilter(request,response)以继续执行应用的其余逻辑。请参阅 API 文档中的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()
}