基本認證
本節詳細介紹了 Spring Security 如何為基於 Servlet 的應用提供對 基本 HTTP 認證 的支援。
本節描述了 HTTP 基本認證在 Spring Security 中的工作原理。首先,我們看到 WWW-Authenticate 頭部被髮送回未認證的客戶端。

上圖構建於我們的 SecurityFilterChain
圖的基礎之上。
首先,使用者向資源
/private
傳送一個未認證的請求,該請求未獲得授權。
Spring Security 的
AuthorizationFilter
透過丟擲 AccessDeniedException
表示該未認證的請求被 拒絕。
由於使用者未認證,
ExceptionTranslationFilter
啟動了 開始認證。配置的 AuthenticationEntryPoint
是 BasicAuthenticationEntryPoint
的一個例項,它傳送一個 WWW-Authenticate 頭部。RequestCache
通常是一個 NullRequestCache
,它不儲存請求,因為客戶端能夠重播它最初請求的請求。
當客戶端收到 WWW-Authenticate
頭部時,它知道應該使用使用者名稱和密碼重試。下圖展示了使用者名稱和密碼處理的流程

上圖構建於我們的 SecurityFilterChain
圖的基礎之上。
當用戶提交使用者名稱和密碼時,
BasicAuthenticationFilter
透過從 HttpServletRequest
中提取使用者名稱和密碼,建立一個 UsernamePasswordAuthenticationToken
,它是一種 Authentication
型別。
接下來,
UsernamePasswordAuthenticationToken
被傳遞給 AuthenticationManager
進行認證。AuthenticationManager
具體是什麼取決於 使用者資訊的儲存方式。
如果認證失敗,則為 失敗。
-
RememberMeServices.loginFail
被呼叫。如果未配置“記住我”,則這是一個空操作。請參閱 API 文件中的RememberMeServices
介面。 -
AuthenticationEntryPoint
被呼叫以觸發 WWW-Authenticate 再次傳送。請參閱 API 文件中的AuthenticationEntryPoint
介面。
如果認證成功,則為 成功。
-
Authentication 被設定在 SecurityContextHolder 上。
-
RememberMeServices.loginSuccess
被呼叫。如果未配置“記住我”,則這是一個空操作。請參閱 API 文件中的RememberMeServices
介面。 -
BasicAuthenticationFilter
呼叫FilterChain.doFilter(request,response)
以繼續執行應用的其餘邏輯。請參閱 API 文件中的BasicAuthenticationFilter
類
預設情況下,Spring Security 的 HTTP 基本認證支援是啟用的。但是,一旦提供了任何基於 Servlet 的配置,就必須明確地提供 HTTP 基本認證。
以下示例展示了一個最小的顯式配置
-
Java
-
XML
-
Kotlin
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) {
http
// ...
.httpBasic(withDefaults());
return http.build();
}
<http>
<!-- ... -->
<http-basic />
</http>
@Bean
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
http {
// ...
httpBasic { }
}
return http.build()
}