基本身份驗證

本節詳細介紹了 Spring Security 如何為基於 Servlet 的應用程式提供 HTTP 基本身份驗證支援。

本節描述了 HTTP 基本身份驗證在 Spring Security 中的工作原理。首先,我們看到 WWW-Authenticate 標頭被髮送回未經身份驗證的客戶端

basicauthenticationentrypoint
圖 1. 傳送 WWW-Authenticate 標頭

上圖基於我們的 SecurityFilterChain 圖。

number 1 首先,使用者對資源 /private 發出未經身份驗證的請求,但該請求未經授權。

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

number 3 由於使用者未透過身份驗證,ExceptionTranslationFilter 啟動“開始身份驗證”。配置的 AuthenticationEntryPointBasicAuthenticationEntryPoint 的一個例項,它傳送一個 WWW-Authenticate 標頭。RequestCache 通常是一個 NullRequestCache,它不儲存請求,因為客戶端能夠重播它最初請求的請求。

當請求帶有 X-Requested-By: XMLHttpRequest 標頭時,預設的 HTTP 基本身份驗證提供程式將抑制 401 響應中的響應正文和 WWW-Authenticate 標頭。這允許前端實現自己的身份驗證程式碼,而不是觸發瀏覽器登入對話方塊。要覆蓋此行為,請實現您自己的 BasicAuthenticationEntryPoint

當客戶端收到 WWW-Authenticate 標頭時,它知道應該使用使用者名稱和密碼重試。下圖顯示了處理使用者名稱和密碼的流程

basicauthenticationfilter
圖 2. 身份驗證使用者名稱和密碼

上圖基於我們的 SecurityFilterChain 圖。

number 1 當用戶提交使用者名稱和密碼時,BasicAuthenticationFilter 透過從 HttpServletRequest 中提取使用者名稱和密碼來建立一個 UsernamePasswordAuthenticationToken,它是一種 Authentication 型別。

number 2 接下來,UsernamePasswordAuthenticationToken 被傳遞到 AuthenticationManager 進行身份驗證。AuthenticationManager 的具體形式取決於 使用者資訊的儲存方式

number 3 如果身份驗證失敗,則為“失敗”。

  1. SecurityContextHolder 被清除。

  2. 呼叫 RememberMeServices.loginFail。如果未配置記住我功能,則此操作為空操作。請參閱 Javadoc 中的 RememberMeServices 介面。

  3. 呼叫 AuthenticationEntryPoint 以再次觸發 WWW-Authenticate 的傳送。請參閱 Javadoc 中的 AuthenticationEntryPoint 介面。

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

預設情況下,Spring Security 的 HTTP 基本身份驗證支援是啟用的。但是,一旦提供了任何基於 Servlet 的配置,HTTP 基本身份驗證必須明確提供。

以下示例顯示了一個最小的、明確的配置

明確的 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()
}
© . This site is unofficial and not affiliated with VMware.