Basic Authentication
本节详细介绍了 Spring Security 如何为基于 servlet 的应用程序提供 Basic HTTP Authentication支持。
本部分介绍 HTTP 基本身份验证如何在 Spring Security 中运行。首先,我们看到 WWW-Authenticate 标头发回给未经身份验证的客户端:
前图基于我们的 SecurityFilterChain 图表构建。
首先,用户向资源 /private 发出未经身份验证的请求,而它没有授权。
Spring Security 的 AuthorizationFilter 指出未经身份验证的请求 Denied 抛出了 AccessDeniedException。
由于用户未经身份验证,所以 ExceptionTranslationFilter 启动 Start Authentication。配置的 AuthenticationEntryPoint 是 {security-api-url}org/springframework/security/web/authentication/www/BasicAuthenticationEntryPoint.html[BasicAuthenticationEntryPoint] 的实例,它发送 WWW 身份验证头。RequestCache 通常是不保存请求的 NullRequestCache,因为客户端能够重复播放其最初请求的请求。
当客户端收到 WWW-Authenticate 头信息时,它便知道它应该用用户名和密码重试。下图显示了处理用户名和密码的流程图:
前图基于我们的 SecurityFilterChain 图表构建。
当用户提交其用户名和密码时,BasicAuthenticationFilter 会通过从 HttpServletRequest 中提取用户名和密码,创建一个 UsernamePasswordAuthenticationToken,它是一种 Authentication。
接下来,将 UsernamePasswordAuthenticationToken 传递到 AuthenticationManager 以进行身份验证。AuthenticationManager 的外观详细信息取决于 user information is stored 的方式。
如果身份验证失败,则_Failure_。
-
调用`RememberMeServices.loginFail`.如果未配置记住我,则这是一个无操作.请参阅 Javadoc 中的 {security-api-url}org/springframework/security/web/authentication/RememberMeServices.html[
RememberMeServices] 接口. -
调用
AuthenticationEntryPoint以触发 WWW-Authenticate 再次发送。参见 Javadoc 中的 {security-api-url}org/springframework/security/web/AuthenticationEntryPoint.html[AuthenticationEntryPoint] 接口。
如果身份验证成功,则 Success
-
调用`RememberMeServices.loginSuccess`.如果未配置记住我,则这是一个无操作.请参阅 Javadoc 中的 {security-api-url}org/springframework/security/web/authentication/RememberMeServices.html[
RememberMeServices] 接口. -
BasicAuthenticationFilter调用FilterChain.doFilter(request,response)以继续进行应用程序逻辑的其余部分。参见 Javadoc 中的 {security-api-url}org/springframework/security/web/authentication/www/BasicAuthenticationFilter.html[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()
}