# OAuth2.0资源服务器

Spring 安全性支持使用两种形式的OAuth2.0不记名代币 (opens new window)来保护端点:

在应用程序已将其权限管理委托给授权服务器 (opens new window)(例如,OKTA或ping标识)的情况下,这很方便。资源服务器可以参考此授权服务器来授权请求。

本节详细介绍了 Spring Security如何为OAuth2.0不记名代币 (opens new window)提供支持。

JWTs (opens new window)不透明令牌 (opens new window)的工作样例都可以在Spring Security Samples repository (opens new window)中找到。

让我们来看看承载令牌身份验证在 Spring 安全性中是如何工作的。首先,我们看到,像基本身份验证一样,WWW-认证 (opens new window)头被发送回未经验证的客户机。

BeareRauthenticationCentryPoint

图1.发送WWW-身份验证报头

上面的图是基于我们的[SecurityFilterChain](../../architecture.html# Servlet-SecurityFilterchain)图构建的。

number 1首先,用户向资源/private发出未经授权的请求。

number 2 Spring security的[FilterSecurityInterceptor](.../授权/authorization/authorization/authorization-requests.html# Servlet-authorization-filtersecurityinterceptor)通过抛出AccessDeniedException表示未经验证的请求是拒绝

number 3由于用户未经过身份验证,[ExceptionTranslationFilter](..../architecture.html# Servlet-ExceptionTranslationFilter)发起启动身份验证。已配置的[AuthenticationEntryPoint](...../authentication/architecture.html# Servlet-authentication-authentryPoint)是[BearerTokenAuthenticationEntryPoint](https://DOCS. Spring.io/ Spring-security/site/DOCS/5.6.2/api/org/springframework/security/oauth2/server/resource/web/bearerertokenauthentrypoint.html)的一个实例,它发送一个WWW-authenticate报RequestCache通常是不保存请求的NullRequestCache,因为客户机能够重放它最初请求的请求。

当客户端收到WWW-Authenticate: Bearer头时,它知道应该使用承载令牌进行重试。下面是正在处理的承载令牌的流程。

BeareRtoKenAuthenticationFilter

图2.不记名令牌的认证

该图构建于我们的[SecurityFilterChain](../../architecture.html# Servlet-SecurityFilterchain)图。

number 1当用户提交其承载令牌时,BearerTokenAuthenticationFilter通过从HttpServletRequest中提取令牌来创建BearerTokenAuthenticationToken,这是[Authentication](../../authentication/architecture.html# Servlet-authentication-authentication)的一种类型。

number 2接下来,将HttpServletRequest传递给AuthenticationManagerResolver,后者选择AuthenticationManager。将BearerTokenAuthenticationToken传递到要进行身份验证的AuthenticationManager中。AuthenticationManager的详细内容取决于你是为JWT还是不透明令牌配置的。

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

  • SecurityContextholder被清除。

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

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

  • 认证设置在SecurityContextholder上。

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

OAuth2授权客户JWT