跳到主要内容

基本认证

QWen Max 中英对照 Basic Basic Authentication

本节提供了有关 Spring Security 为基于 servlet 的应用程序提供基本 HTTP 身份验证支持的详细信息。

本节描述了HTTP Basic认证在Spring Security中的工作原理。首先,我们看到WWW-Authenticate头部被发送回未认证的客户端:

basicauthenticationentrypoint

图 1. 发送 WWW-Authenticate 标头

上图基于我们的SecurityFilterChain图构建。

1 首先,用户向其未被授权的资源 /private 发起一个未经身份验证的请求。

2 Spring Security 的 AuthorizationFilter 通过抛出 AccessDeniedException 异常来表示未经身份验证的请求被拒绝

3 由于用户未通过身份验证,ExceptionTranslationFilter 启动开始身份验证。配置的 AuthenticationEntryPointBasicAuthenticationEntryPoint 的实例,它发送一个 WWW-Authenticate 头。RequestCache 通常是一个 NullRequestCache,不保存请求,因为客户端能够重放其最初请求的请求。

当客户端收到 WWW-Authenticate 标头时,它就知道应该使用用户名和密码重试。下图显示了处理用户名和密码的流程:

basicauthenticationfilter

图 2. 验证用户名和密码

上图基于我们的SecurityFilterChain图构建。

1 当用户提交其用户名和密码时,BasicAuthenticationFilter 会创建一个 UsernamePasswordAuthenticationToken,这是一种 Authentication,通过从 HttpServletRequest 中提取用户名和密码来实现。

2 接下来,UsernamePasswordAuthenticationToken 被传递给 AuthenticationManager 进行认证。AuthenticationManager 的具体细节取决于用户信息的存储方式

3 如果身份验证失败,则为 Failure

  1. SecurityContextHolder 被清空。

  2. 调用 RememberMeServices.loginFail。如果未配置记住我功能,这将是一个无操作。请参阅 Javadoc 中的 RememberMeServices 接口。

  3. 调用 AuthenticationEntryPoint 以触发再次发送 WWW-Authenticate。请参阅 Javadoc 中的 AuthenticationEntryPoint 接口。

4 如果身份验证成功,则为Success

  1. 认证SecurityContextHolder 上设置。

  2. 调用 RememberMeServices.loginSuccess。如果未配置记住我功能,这将是一个空操作。请参阅 Javadoc 中的 RememberMeServices 接口。

  3. BasicAuthenticationFilter 调用 FilterChain.doFilter(request,response) 以继续其余的应用程序逻辑。请参阅 Javadoc 中的 BasicAuthenticationFilter 类。

默认情况下,Spring Security 的 HTTP 基本认证支持是启用的。然而,一旦提供了任何基于 servlet 的配置,就必须显式地提供 HTTP 基本认证。

以下示例显示了一个最小的、显式的配置:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) {
http
// ...
.httpBasic(withDefaults());
return http.build();
}
java