对于最新的稳定版本,请使用 Spring Security 6.5.3! |
基本身份验证
本节详细介绍了 Spring Security 如何为基于 servlet 的应用程序提供对基本 HTTP 身份验证的支持。
本节介绍 HTTP 基本身份验证在 Spring Security 中的工作原理。 首先,我们看到 WWW-Authenticate 标头被发送回未经身份验证的客户端:

上图基于我们的SecurityFilterChain
图。
首先,用户向资源发出未经身份验证的请求
/private
它没有被授权。
Spring Security 的
FilterSecurityInterceptor
表示通过抛出AccessDeniedException
.
由于用户未经过身份验证,
ExceptionTranslationFilter
启动启动身份验证。
配置的AuthenticationEntryPoint
是BasicAuthenticationEntryPoint
,它发送一个 WWW-Authenticate 标头。
这RequestCache
通常是NullRequestCache
这不会保存请求,因为客户端能够重播它最初请求的请求。
当客户端收到WWW-Authenticate
标头,它知道它应该使用用户名和密码重试。
下图显示了正在处理的用户名和密码的流:

上图基于我们的SecurityFilterChain
图。
当用户提交用户名和密码时,
BasicAuthenticationFilter
创建一个UsernamePasswordAuthenticationToken
,这是一种Authentication
通过从HttpServletRequest
.
接下来,
UsernamePasswordAuthenticationToken
被传递到AuthenticationManager
待认证。
什么的细节AuthenticationManager
看起来取决于用户信息的存储方式。
如果身份验证失败,则失败。
-
RememberMeServices.loginFail
被调用。 如果记住我没有配置,这是一个无作。 请参阅RememberMeServices
Javadoc 中的接口。 -
AuthenticationEntryPoint
被调用以触发再次发送 WWW-Authenticate。 请参阅AuthenticationEntryPoint
Javadoc 中的接口。
如果身份验证成功,则成功。
-
身份验证是在 SecurityContextHolder 上设置的。
-
RememberMeServices.loginSuccess
被调用。 如果记住我没有配置,这是一个无作。 请参阅RememberMeServices
Javadoc 中的接口。 -
这
BasicAuthenticationFilter
调用FilterChain.doFilter(request,response)
以继续其余的应用程序逻辑。 请参阅BasicAuthenticationFilter
Javadoc 中的类
默认情况下,Spring Security 的 HTTP 基本身份验证支持处于启用状态。 但是,一旦提供了任何基于 servlet 的配置,就必须显式提供 HTTP Basic。
以下示例显示了最小的显式配置:
-
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()
}