Spring Security登錄驗證流程源碼解析

一、登錄認證基於過濾器鏈

Spring Security的登錄驗證流程核心就是過濾器鏈。當一個請求到達時按照過濾器鏈的順序依次進行處理,通過所有過濾器鏈的驗證,就可以訪問API接口了。

file

SpringSecurity提供了多種登錄認證的方式,由多種Filter過濾器來實現,比如:

  • BasicAuthenticationFilter實現的是HttpBasic模式的登錄認證
  • UsernamePasswordAuthenticationFilter實現用戶名密碼的登錄認證
  • RememberMeAuthenticationFilter實現登錄認證的“記住我”的功能
  • SmsCodeAuthenticationFilter實現短信驗證碼登錄認證
  • SocialAuthenticationFilter實現社交媒體方式登錄認證的處理
  • Oauth2AuthenticationProcessingFilter和Oauth2ClientAuthenticationProcessingFilter實現Oauth2的鑑權方式

根據我們不同的需求實現及配置,不同的Filter會被加載到應用中。

二、結合源碼講解登錄驗證流程

我們就以用戶名、密碼登錄方式爲例講解一下Spring Security的登錄認證流程。

file

2.1 UsernamePasswordAuthenticationFilter

該過濾器封裝用戶基本信息(用戶名、密碼),定義登錄表單數據接收相關的信息。如:

  • 默認的表單用戶名密碼input框name是username、password
  • 默認的處理登錄請求路徑是/login、使用POST方法

file
file

2.2 AbstractAuthenticationProcessingFilter的doFilter方法的驗證過程

UsernamePasswordAuthenticationFilter繼承自抽象類AbstractAuthenticationProcessingFilter,該抽象類定義了驗證成功與驗證失敗的處理方法。
file

2.3 驗證成功之後的Handler和驗證失敗之後的handler

file

也就是說當我們需要自定義驗證成功或失敗的處理方法時,要去實現AuthenticationSuccessHandler或AuthenticationfailureHandler接口

file

三、登錄驗證內部細節

3.1多種認證方式的管理 ProviderManager

ProviderManager用繼承於AuthenticationManager是登錄驗證的核心類。ProviderManager保管了多個AuthenticationProvider,用於不同類型的登錄驗證。比如:

  • RememberMeAuthenticationProvider定義了“記住我”功能的登錄驗證邏輯
  • DaoAuthenticationProvider加載數據庫用戶信息,進行用戶密碼的登錄驗證
public class ProviderManager implements AuthenticationManager, MessageSourceAware, InitializingBean {
    ……
    private List<AuthenticationProvider> providers;
    ……

下文是ProviderManager的核心源碼,遍歷不同登錄驗證的AuthenticationProvider,只有當這種方式被支持的時候,才執行具體的登錄驗證邏輯。
file

3.2 登錄認證接口 AuthenticationProvider

public interface AuthenticationProvider {
    Authentication authenticate(Authentication var1) throws AuthenticationException;

    boolean supports(Class<?> var1);
}

AuthenticationProvider的實現類定義了具體的登錄驗證邏輯

file

3.3 數據庫加載用戶信息 DaoAuthenticationProvider

public class DaoAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {

從數據庫獲取用戶信息源碼

file

所以當我們需要加載用戶信息進行登錄驗證的時候,我們需要實現UserDetailsService接口,重寫loadUserByUsername方法,參數是用戶輸入的用戶名。返回值是UserDetails

期待您的關注

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章