OAuth 2.0 資源伺服器

Spring Security 支援透過使用兩種形式的 OAuth 2.0 不記名令牌(Bearer Tokens)來保護端點

  • JWT

  • 不透明令牌

這在應用程式將其許可權管理委託給授權伺服器(例如 Okta 或 Ping Identity)的情況下非常方便。資源伺服器可以諮詢此授權伺服器以授權請求。

本節詳細介紹了 Spring Security 如何為 OAuth 2.0 不記名令牌提供支援。

關於 JWT不透明令牌 的工作示例可在 Spring Security 示例倉庫中找到。

現在我們可以考慮不記名令牌認證在 Spring Security 中的工作方式。首先,我們看到,與 基本認證一樣,WWW-Authenticate 頭會發送回未認證的客戶端

bearerauthenticationentrypoint
圖 1. 傳送 WWW-Authenticate 頭

上圖基於我們的 SecurityFilterChain 圖。

number 1 首先,使用者向未經授權的 /private 資源發出未經認證的請求。

number 2 Spring Security 的 AuthorizationFilter 透過丟擲 AccessDeniedException 來表示未經身份驗證的請求被“拒絕”。

number 3 由於使用者未認證,ExceptionTranslationFilter 啟動 認證開始。配置的 AuthenticationEntryPointBearerTokenAuthenticationEntryPoint 的例項,它傳送一個 WWW-Authenticate 頭。RequestCache 通常是一個 NullRequestCache,它不儲存請求,因為客戶端能夠重放其最初請求的請求。

當客戶端收到 WWW-Authenticate: Bearer 頭時,它知道應該使用不記名令牌重試。下圖展示了不記名令牌的處理流程

bearertokenauthenticationfilter
圖 2. 認證不記名令牌

該圖基於我們的 SecurityFilterChain 圖表構建。

number 1 當用戶提交不記名令牌時,BearerTokenAuthenticationFilter 透過從 HttpServletRequest 中提取令牌來建立一個 BearerTokenAuthenticationToken,它是一種 Authentication 型別。

number 2 接下來,HttpServletRequest 被傳遞給 AuthenticationManagerResolver,它選擇 AuthenticationManagerBearerTokenAuthenticationToken 被傳遞到 AuthenticationManager 進行認證。AuthenticationManager 的具體形式取決於您是配置為 JWT 還是 不透明令牌

number 3 如果認證失敗,則 失敗

  • SecurityContextHolder 被清除。

  • AuthenticationEntryPoint 被呼叫,以再次觸發 WWW-Authenticate 頭的傳送。

number 4 如果身份驗證成功,則為“成功”。

© . This site is unofficial and not affiliated with VMware.