OAuth 2.0 資源伺服器

Spring Security 透過使用兩種形式的 OAuth 2.0 Bearer 令牌 來支援保護端點

  • JWT

  • 不透明令牌

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

本節詳細介紹 Spring Security 如何支援 OAuth 2.0 Bearer 令牌

Spring Security 示例倉庫 中提供了 JWT不透明令牌 的可用工作示例。

現在我們可以考慮 Bearer 令牌認證在 Spring Security 中如何工作。首先,我們看到,與 Basic 認證 一樣,WWW-Authenticate 頭會被髮送回未認證的客戶端

bearerauthenticationentrypoint
圖 1. 傳送 WWW-Authenticate 頭

上圖基於我們的 SecurityFilterChain 圖。

數字 1 首先,使用者對 /private 資源發起一個未經認證的請求,該使用者未被授權訪問此資源。

數字 2 Spring Security 的 AuthorizationFilter 透過丟擲 AccessDeniedException 來指示未經認證的請求被 拒絕

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

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

bearertokenauthenticationfilter
圖 2. 認證 Bearer 令牌

該圖基於我們的 SecurityFilterChain 圖。

數字 1 當用戶提交其 bearer 令牌時,BearerTokenAuthenticationFilter 透過從 HttpServletRequest 中提取令牌來建立 BearerTokenAuthenticationToken,它是一種 Authentication 型別。

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

數字 3 如果認證失敗,則 失敗

  • SecurityContextHolder 被清空。

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

數字 4 如果認證成功,則 成功

  • Authentication 被設定到 SecurityContextHolder 上。

  • BearerTokenAuthenticationFilter 呼叫 FilterChain.doFilter(request,response) 繼續執行應用程式的其餘邏輯。