Basic Authentication

Basic Authentication

本节详细介绍了 Spring Security 如何为基于 servlet 的应用程序提供对基本 HTTP 身份验证的支持。

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

上图基于 SecurityFilterChain 图。

  1. 首先,用户向未获得授权的资源 /private 发出未经身份验证的请求。
  2. Spring Security 的 AuthorizationFilter 通过抛出 AccessDeniedException 来指示未经身份验证的请求被拒绝。
  3. 由于用户未经过身份验证,因此 ExceptionTranslationFilter 会启动 Start Authentication。配置的 AuthenticationEntryPoint 是 BasicAuthenticationEntryPoint 的实例,它发送 WWW-Authenticate 标头。RequestCache 通常是不保存请求的 NullRequestCache,因为 Client 端能够重放它最初请求的请求。

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

上图基于 SecurityFilterChain 图。

  1. 当用户提交他们的用户名和密码时,BasicAuthenticationFilter 会创建一个 UsernamePasswordAuthenticationToken,这是一种通过从 HttpServletRequest 中提取用户名和密码来进行验证的类型。
  2. 接下来,将 UsernamePasswordAuthenticationToken 传递到 AuthenticationManager 中进行身份验证。AuthenticationManager 的外观详细信息取决于用户信息的存储方式。
  3. 如果身份验证失败,则失败。
    1. SecurityContextHolder被清除。
    2. 调用 RememberMeServices.loginFail。如果未配置 Remember me,则为 no-op。请参阅 Javadoc 中的 RememberMeServices 接口。
    3. 调用 AuthenticationEntryPoint 以触发再次发送 WWW-Authenticate。请参阅 Javadoc 中的 AuthenticationEntryPoint 接口。
  4. 如果身份验证成功,则为 Success。

    1. Authentication在SecurityContextHolder上设置。

    2. 调用 RememberMeServices.loginSuccess 时。如果未配置 Remember me,则为 no-op。请参阅 Javadoc 中的 RememberMeServices 接口。

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

默认情况下,Spring Security 的 HTTP 基本身份验证支持处于启用状态。但是,一旦提供了任何基于 servlet 的配置,就必须显式提供 HTTP Basic。

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

Explicit HTTP Basic Configuration

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) {
    http
        // ...
        .httpBasic(withDefaults());
    return http.build();
}
posted @   红拂夜奔  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示