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

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

该图建立在我们的SecurityFilterChain
图。
当用户提交其 bearer token 时,
BearerTokenAuthenticationFilter
创建一个BearerTokenAuthenticationToken
这是一种Authentication
通过从HttpServletRequest
.
接下来,
HttpServletRequest
传递给AuthenticationManagerResolver
,这会选择AuthenticationManager
.这BearerTokenAuthenticationToken
传递到AuthenticationManager
进行身份验证。
什么的细节AuthenticationManager
取决于您是配置了 JWT 还是 Opaque 令牌。
如果身份验证失败,则失败
-
这
AuthenticationEntryPoint
以触发 WWW-Authenticate 标头以再次发送。
如果身份验证成功,则为 Success。
-
这
BearerTokenAuthenticationFilter
调用FilterChain.doFilter(request,response)
以继续执行 Application Logic 的其余部分。