对于最新的稳定版本,请使用 Spring Security 6.4.1spring-doc.cadn.net.cn

OAuth 2.0 资源服务器

Spring Security 支持使用两种形式的 OAuth 2.0 不记名令牌来保护端点:spring-doc.cadn.net.cn

在应用程序已将其权限管理委托给授权服务器(例如,Okta 或 Ping Identity)的情况下,这非常方便。 资源服务器可以查阅此授权服务器来授权请求。spring-doc.cadn.net.cn

本节详细介绍了 Spring Security 如何为 OAuth 2.0 Bearer Tokens 提供支持。spring-doc.cadn.net.cn

现在我们可以考虑 Bearer Token Authentication 在 Spring Security 中是如何工作的。 首先,我们看到,与基本身份验证一样,WWW-Authenticate 标头被发送回未经身份验证的客户端:spring-doc.cadn.net.cn

BearerAuthenticationEntryPoint
图 1.发送 WWW-Authenticate 报头

上图建立在我们的SecurityFilterChain图。spring-doc.cadn.net.cn

数字 1首先,用户向/private用户未获得授权的资源。spring-doc.cadn.net.cn

编号 2Spring Security 的FilterSecurityInterceptor表示未经身份验证的请求被拒绝,方法是抛出AccessDeniedException.spring-doc.cadn.net.cn

编号 3由于用户未经过身份验证,因此ExceptionTranslationFilter启动 Start Authentication。 配置的AuthenticationEntryPointBearerTokenAuthenticationEntryPoint,它会发送一个WWW-Authenticate页眉。 这RequestCache通常是NullRequestCache这不会保存请求,因为 Client 端能够重放它最初请求的请求。spring-doc.cadn.net.cn

当客户端收到WWW-Authenticate: Bearer标头,它知道它应该使用 Bearer 令牌重试。 下图显示了正在处理的持有者令牌的流程:spring-doc.cadn.net.cn

bearertokenauthenticationfilter
图 2.验证 Bearer Token

该图建立在我们的SecurityFilterChain图。spring-doc.cadn.net.cn

数字 1当用户提交其 bearer token 时,BearerTokenAuthenticationFilter创建一个BearerTokenAuthenticationToken这是一种Authentication通过从HttpServletRequest.spring-doc.cadn.net.cn

编号 2接下来,HttpServletRequest传递给AuthenticationManagerResolver,这会选择AuthenticationManager.这BearerTokenAuthenticationToken传递到AuthenticationManager进行身份验证。 什么的细节AuthenticationManager取决于您是配置了 JWT 还是 Opaque 令牌spring-doc.cadn.net.cn

编号 3如果身份验证失败,则失败spring-doc.cadn.net.cn

编号 4如果身份验证成功,则为 Successspring-doc.cadn.net.cn