对于最新的稳定版本,请使用 Spring Security 6.5.3! |
OAuth 2.0 资源服务器
Spring Security 支持使用两种形式的 OAuth 2.0 持有者Tokens保护端点:
-
不透明Tokens
这在应用程序已将其权限管理委托给授权服务器(例如 Okta 或 Ping Identity)的情况下非常方便。 资源服务器可以查阅此授权服务器来授权请求。
本节详细介绍了 Spring Security 如何为 OAuth 2.0 不记名Tokens提供支持。
JWT 和 Opaque Token 的工作示例可在 Spring Security Samples 存储库中找到。 |
让我们来看看 Bearer Token Authentication 在 Spring Security 中是如何工作的。 首先,我们看到,与基本身份验证一样,WWW-Authenticate 标头被发送回未经身份验证的客户端。

上图建立在我们的SecurityFilterChain
图。
首先,用户向资源发出未经身份验证的请求
/private
它没有被授权。
Spring Security 的
FilterSecurityInterceptor
表示通过抛出AccessDeniedException
.
由于用户未经过身份验证,
ExceptionTranslationFilter
启动启动身份验证。
配置的AuthenticationEntryPoint
是BearerTokenAuthenticationEntryPoint
它发送一个 WWW-Authenticate 标头。
这RequestCache
通常是NullRequestCache
这不会保存请求,因为客户端能够重播它最初请求的请求。
当客户端收到WWW-Authenticate: Bearer
标头,它知道它应该使用持有者Tokens重试。
下面是正在处理的不记名Tokens的流程。

该图建立在我们的SecurityFilterChain
图。
当用户提交其不记名Tokens时,
BearerTokenAuthenticationFilter
创建一个BearerTokenAuthenticationToken
这是一种Authentication
通过从HttpServletRequest
.
接下来,
HttpServletRequest
传递给AuthenticationManagerResolver
,它选择AuthenticationManager
.这BearerTokenAuthenticationToken
被传递到AuthenticationManager
待认证。
什么的细节AuthenticationManager
看起来取决于您是配置了 JWT 还是不透明Tokens。
如果身份验证失败,则失败
-
这
AuthenticationEntryPoint
被调用以触发再次发送 WWW-Authenticate 标头。
如果身份验证成功,则成功。
-
身份验证是在 SecurityContextHolder 上设置的。
-
这
BearerTokenAuthenticationFilter
调用FilterChain.doFilter(request,response)
以继续其余的应用程序逻辑。