# 基本身份验证
本节详细介绍了 Spring 安全性如何为基于 Servlet 的应用程序提供基本 HTTP 认证 (opens new window)支持。
让我们来看看 HTTP Basic 身份验证在 Spring 安全性中是如何工作的。首先,我们看到WWW-认证 (opens new window)头被发送回未经验证的客户端。
图 1。发送 WWW-身份验证报头
该图构建于我们的[SecurityFilterChain
](../../architecture.html# Servlet-SecurityFilterchain)图。
首先,用户向资源
/private
发出未经授权的请求。
Spring security 的[
FilterSecurityInterceptor
](.../授权/authorization/authorization/authorization-requests.html# Servlet-authorization-filtersecurityinterceptor)通过抛出AccessDeniedException
表示未经验证的请求是拒绝。
由于用户未经过身份验证,[
ExceptionTranslationFilter
](..../architecture.html# Servlet-ExceptionTranslationFilter)发起启动身份验证。配置的[AuthenticationEntryPoint
](../architecture.html# Servlet-authentication-authentryPoint)是[BasicAuthenticationEntryPoint
](https://DOCS. Spring.io/ Spring-security/site/DOCS/5.6.2/api/org/springframework/security/web/authentification/WWW/basicauthentrypoint.html)的一个实例,它发送一个 WWW-authenticate 报头。RequestCache
通常是不保存请求的NullRequestCache
,因为客户机能够重放它最初请求的请求。
当客户端接收到 WWW-Authenticate 报头时,它知道应该使用用户名和密码重试。下面是正在处理的用户名和密码的流程。
图 2。验证用户名和密码
这个图是基于我们的[SecurityFilterChain
](../../architecture.html# Servlet-SecurityFilterchain)图构建的。
当用户提交他们的用户名和密码时,
BasicAuthenticationFilter
通过从HttpServletRequest
中提取用户名和密码,创建一个UsernamePasswordAuthenticationToken
,这是一种[Authentication
](../architecture.html# Servlet-authentication-authentication)的类型。
接下来,将
UsernamePasswordAuthenticationToken
传递到AuthenticationManager
中以进行身份验证。AuthenticationManager
的详细内容取决于用户信息被存储的方式。
如果身份验证失败,则失败
调用
RememberMeServices.loginFail
。如果 Remember Me 没有配置,这是一个禁止操作。调用
AuthenticationEntryPoint
以触发再次发送 WWW-身份验证。
如果身份验证成功,则成功。
认证设置在SecurityContextholder 上。
调用
RememberMeServices.loginSuccess
。如果 Remember Me 没有配置,这是一个禁止操作。BasicAuthenticationFilter
调用FilterChain.doFilter(request,response)
以继续应用程序逻辑的其余部分。
Spring 默认情况下启用了 Security 的 HTTP Basic 身份验证支持。然而,只要提供了任何基于 Servlet 的配置,就必须显式地提供 HTTP BASIC。
可以在下面找到最小的显式配置:
例 1。显式 HTTP 基本配置
爪哇
protected void configure(HttpSecurity http) {
http
// ...
.httpBasic(withDefaults());
}
XML
<http>
<!-- ... -->
<http-basic />
</http>
Kotlin
fun configure(http: HttpSecurity) {
http {
// ...
httpBasic { }
}
}