Spring Security 支持使用两种形式的 OAuth 2.0 持有者令牌来保护端点:
-
不透明令牌
这在应用程序已将其权限管理委派给授权服务器(例如,Okta 或 Ping Identity)的情况下非常方便。 资源服务器可以查阅此授权服务器来授权请求。
本节详细介绍了 Spring Security 如何提供对 OAuth 2.0 持有者令牌的支持。
JWT 和不透明令牌的工作示例都可以在 Spring Security Samples 存储库中找到。 |
JWT 和不透明令牌的工作示例都可以在 Spring Security Samples 存储库中找到。 |
现在我们可以考虑 Bearer Token Authentication 在 Spring Security 中的工作方式。 首先,我们看到,与基本身份验证一样,WWW-Authenticate 标头被发送回未经身份验证的客户端:
![bearerAuthentication入口点](https://docs.spring.io/spring-security/reference/6.3/_images/servlet/oauth2/bearerauthenticationentrypoint.png)
上图基于我们的 SecurityFilterChain
图构建。
首先,用户向用户未授权的资源发出未经身份验证的请求。
/private
Spring Security 的
AuthorizationFilter
通过抛出 .AccessDeniedException
由于用户未通过身份验证,
因此 ExceptionTranslationFilter
将启动启动身份验证。
配置的 AuthenticationEntryPoint
是 BearerTokenAuthenticationEntryPoint
的实例,用于发送标头。
通常不保存请求,因为客户端能够重播它最初请求的请求。WWW-Authenticate
RequestCache
NullRequestCache
当客户端收到标头时,它知道它应该使用持有者令牌重试。
下图显示了正在处理的持有者令牌的流:WWW-Authenticate: Bearer
![BearerTokenAuthentication过滤器](https://docs.spring.io/spring-security/reference/6.3/_images/servlet/oauth2/bearertokenauthenticationfilter.png)
该图基于我们的 SecurityFilterChain
图构建。
当用户提交其持有者令牌时
,通过从 .
BearerTokenAuthenticationFilter
BearerTokenAuthenticationToken
HttpServletRequest
接下来,将 传递给 ,后者选择 .将传递到要进行身份验证的 中。
外观的详细信息取决于您是针对 JWT 还是不透明令牌进行配置。
HttpServletRequest
AuthenticationManagerResolver
AuthenticationManager
BearerTokenAuthenticationToken
AuthenticationManager
AuthenticationManager
如果身份验证失败,则失败
-
调用 以触发再次发送 WWW-Authenticate 标头。
AuthenticationEntryPoint
如果身份验证成功,则为成功。
-
身份验证是在 SecurityContextHolder 上设置的。
-
调用以继续执行应用程序逻辑的其余部分。
BearerTokenAuthenticationFilter
FilterChain.doFilter(request,response)