基本认证
本节详细介绍了 Spring Security 如何为基于 Servlet 的应用程序提供HTTP 基本身份验证支持。
本节介绍 HTTP 基本身份验证在 Spring Security 中的工作原理。 首先,我们会看到 WWW-Authenticate 头部被发送回未经身份验证的客户端:
上图基于我们的 SecurityFilterChain 图构建。
首先,用户向资源发起未通过身份验证的请求/private未经授权不得访问。
Spring Security 的AuthorizationFilter表示未认证的请求是拒绝访问通过抛出AccessDeniedException.
由于用户未通过身份验证,ExceptionTranslationFilter启动开始身份验证.
已配置的AuthenticationEntryPoint是BasicAuthenticationEntryPoint,它会发送一个 WWW-Authenticate 头。
TheRequestCache通常是NullRequestCache由于客户端能够重放其最初请求的请求,因此不会保存该请求。
|
默认的 HTTP Basic Auth 提供程序将在请求包含 |
当客户端收到 WWW-Authenticate 响应头时,它就知道应该使用用户名和密码重新尝试请求。
下图展示了用户名和密码的处理流程:
上图基于我们的 SecurityFilterChain 图构建。
当用户提交用户名和密码时,BasicAuthenticationFilter创建UsernamePasswordAuthenticationToken,这是一种类型的Authentication通过提取用户名和密码HttpServletRequest.
接下来,UsernamePasswordAuthenticationToken被传递到AuthenticationManager需要身份验证。
详细信息如下AuthenticationManager看起来取决于用户信息已存储.
如果身份验证失败,则失败.
-
SecurityContextHolder 已被清空。
-
RememberMeServices.loginFail被调用。 如果未配置“记住我”功能,此操作将无效果。 请参阅 Javadoc 中的RememberMeServices接口。 -
AuthenticationEntryPoint被调用以再次触发发送 WWW-Authenticate。 请参阅 Javadoc 中的AuthenticationEntryPoint接口。
如果认证成功,则成功.
-
任何已认证的
Authentication在SecurityContextHolder中都会被加载,其权限将被添加到返回的Authentication中。-
Authentication 被设置到 SecurityContextHolder 上。
-
RememberMeServices.loginSuccess被调用。 如果未配置“记住我”功能,此操作将无效果。 请参阅 Javadoc 中的RememberMeServices接口。 -
The
BasicAuthenticationFilter调用FilterChain.doFilter(request,response)以继续执行其余的应用程序逻辑。 请参阅 Javadoc 中的BasicAuthenticationFilter类
-
默认情况下,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()
}