跳到主要内容

OAuth 2.0 资源服务器

QWen Max 中英对照 OAuth2 Resource Server OAuth 2.0 Resource Server

Spring Security 支持使用两种形式的 OAuth 2.0 Bearer Tokens 来保护端点:

  • JWT

  • Opaque Tokens

在应用程序将其权限管理委托给授权服务器(例如,Okta 或 Ping Identity)的情况下,这一点非常方便。资源服务器可以咨询该授权服务器以授权请求。

本节详细介绍了 Spring Security 如何为 OAuth 2.0 Bearer Tokens 提供支持。

备注

可用的工作示例包括 JWTsOpaque Tokens,这些示例可以在 Spring Security 示例仓库 中找到。

现在我们可以考虑 Bearer Token Authentication 在 Spring Security 中是如何工作的。首先,我们看到,与 Basic Authentication 一样,会向未认证的客户端发送 WWW-Authenticate 头:

bearerauthenticationentrypoint

图 1. 发送 WWW-Authenticate 标头

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

1 首先,用户对 /private 资源发起一个未经身份验证的请求,而该用户并没有此资源的访问权限。

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

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

当客户端收到 WWW-Authenticate: Bearer 头时,它就知道应该使用承载令牌重试。下图显示了承载令牌的处理流程:

bearertokenauthenticationfilter

图 2. 验证 Bearer Token

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

1 当用户提交他们的bearer token时,BearerTokenAuthenticationFilter 会从 HttpServletRequest 中提取token,并创建一个 BearerTokenAuthenticationToken,这是一种 Authentication 类型。

2 接下来,HttpServletRequest 被传递给 AuthenticationManagerResolver,后者选择 AuthenticationManagerBearerTokenAuthenticationToken 被传递到 AuthenticationManager 进行认证。AuthenticationManager 的具体细节取决于您配置的是 JWT 还是 不透明令牌

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

  • SecurityContextHolder 被清空。

  • AuthenticationEntryPoint 被调用以触发再次发送 WWW-Authenticate 头。

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

  • 认证 设置在 SecurityContextHolder 上。

  • BearerTokenAuthenticationFilter 调用 FilterChain.doFilter(request,response) 以继续其余的应用程序逻辑。

节总结

📄️ 不透明令牌

如在Minimal Dependencies for JWT中所述,大多数资源服务器支持都集中在spring-security-oauth2-resource-server中。然而,除非提供了一个自定义的OpaqueTokenIntrospector,否则资源服务器将回退到NimbusOpaqueTokenIntrospector。这意味着为了拥有一个支持不透明Bearer Tokens的最小工作的资源服务器,同时需要spring-security-oauth2-resource-server和oauth2-oidc-sdk。请参考spring-security-oauth2-resource-server以确定oauth2-oidc-sdk的正确版本。