在Spring Security中如何獲取AuthenticationManager對象?

来源:https://www.cnblogs.com/cnblog-user/archive/2022/11/24/16923661.html
-Advertisement-
Play Games

一.小結 1.程式模塊化和可重用性是軟體工程的中心目標之一。java提供了很多有助於完成這一目標的有效結構。方法就是一個這樣的結構。 2.方法指定方法的修飾符,返回值類型,方法名和參數。比如靜態修飾符static。 3.方法可以返回一個值。返回值類型returnValueType是方法要返回的值數據 ...


有時需要使用AuthenticationManager(以下簡稱Manager)對象,可是這個對象不是Bean,沒有直接保存在Spring的Bean庫中。那麼如何獲取Spring Security中的這個對象呢?

在Spring Security 5.7.0-M2之前,通常會擴展WebSecurityConfigurerAdapter(以下簡稱Adapter)類來自定義網路安全配置。Adapter類中有一個方法authenticationManager()可以提供Manager對象。但是從Spring Security 5.7.0-M2開始,Adapter類就被棄用,再用此類中的authenticationManager()方法獲取Manager對象就不合適了。

以下是Adapter#authenticationManager()方法的源碼。

protected AuthenticationManager authenticationManager() throws Exception {
    if (!this.authenticationManagerInitialized) {
        configure(this.localConfigureAuthenticationBldr);
        if (this.disableLocalConfigureAuthenticationBldr) {
            this.authenticationManager = this.authenticationConfiguration.getAuthenticationManager();
        } else {
            this.authenticationManager = this.localConfigureAuthenticationBldr.build();
    }
    this.authenticationManagerInitialized = true;
    }
    return this.authenticationManager;
}

可以發現在該方法中使用Adapter類的私有欄位authenticationConfiguration的getAuthenticationManager()方法獲取Manager對象。而欄位authenticationConfiguration是使用方法setAthenticationConfiguration()自動註入的,所以Spring的Bean庫中存在Manager對象。由此可得到如下獲取AuthenticationManager對象的方案一。

方案一:從Spring的Bean庫中獲取AuthenticationConfiguration(以下簡稱Configuration)對象,然後使用Configuration對象的getAuthenticationManager()方法獲取Manager對象。(關於如何從Spring中獲取Bean,本文不作介紹,請讀者自行查閱資料瞭解)

繼續查看Configuration#getAuthenticationManager()方法的源碼。

public AuthenticationManager getAuthenticationManager() throws Exception {
    if (this.authenticationManagerInitialized) {
        return this.authenticationManager;
    }
    AuthenticationManagerBuilder authBuilder = this.applicationContext.getBean(AuthenticationManagerBuilder.class);
    if (this.buildingAuthenticationManager.getAndSet(true)) {
        return new AuthenticationManagerDelegator(authBuilder);
    }
    for (GlobalAuthenticationConfigurerAdapter config : this.globalAuthConfigurers) {
        authBuilder.apply(config);
    }
    this.authenticationManager = authBuilder.build();
    if (this.authenticationManager == null) {
        this.authenticationManager = getAuthenticationManagerBean();
    }
    this.authenticationManagerInitialized = true;
    return this.authenticationManager;
}

源碼中展示的流程如下。

① 如果Configuration對象中已保存有Manager對象,則返回該對象。

② 如果Configuration對象中沒有Manager對象,則從Spring的Bean庫中獲取AuthenticationManagerBuilder(以下簡稱Builder)對象。

③ 如果已經用Builder對象構建了Manager對象,則返回一個使用Builder對象初始化的AuthenticationManagerDelegator對象。

④ AuthenticationManagerDelegator是Manager的子類。該類代理了另一個Manager對象,被代理的Manager對象是使用Builder對象的getObject()方法獲得的。Builder#getObject()的代碼表明,在調用該方法前,需要先在Builder對象內構建一個Manager。也就是說可以從Spring的Bean庫中獲取Builder對象,然後用它的getObject()方法獲得Manager對象。

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (this.delegate != null) {
        return this.delegate.authenticate(authentication);
    }
    synchronized (this.delegateMonitor) {
        if (this.delegate == null) {
            this.delegate = this.delegateBuilder.getObject();
            this.delegateBuilder = null;
        }
    }
    return this.delegate.authenticate(authentication);
}

⑤ 如果尚未使用Builder對象構建Manager對象,則先把Configuration的私有欄位globalAuthConfigurers的數據應用在Builder對象上(私有欄位globalAuthConfigurers是通過方法setGlobalAuthConfigurers()自動註入的)。

⑥ 然後使用Builder對象的build()方法構建Manager對象。

⑦ 在Builder#build()方法中,第一次調用該方法會使用doBuild()方法生成Manager對象(不分析doBuild()方法),並將這個對象緩存下來。以後再調用build()方法將會拋出AlreadyBuiltException異常。也就是說可以從Spring的Bean庫中獲取Builder對象,然後用它的build()方法獲得Manager對象。

@Override
public final O build() throws Exception {
    if (this.building.compareAndSet(false, true)) {
        this.object = doBuild();
        return this.object;
    }
    throw new AlreadyBuiltException("This object has already been built");
}

⑧ 如果Builder對象未能成功構建Manager對象,則使用Configuration的私有方法lazyBean()方法獲取Manager對象(不分析lazyBean()方法)。

上述流程表明,可以從Spring的Bean庫中獲取AuthenticationManagerBuilder對象,然後使用該對象的build()方法或getObject()方法獲取AuthenticationManager對象。獲取AuthenticationManager對象的方案二如下。

方案二:從Spring的Bean庫中獲取AuthenticationManagerBuilder對象,首先調用該對象的build()方法獲取Manager對象,並對方法調用捕獲AlreadyBuiltException異常。若捕獲到異常,則在異常處理代碼中調用Builder對象的getObject()方法獲取Manager對象。

方案二可能有缺陷。在Configuration#getAuthenticationManager()方法的源碼中可以看到步驟⑤對Builder對象對象做了處理,而方案二並沒有做這種處理,推薦使用方案一。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Android開發之線程間通信 當我們的軟體啟動的時候,電腦會分配進程給到我們運行的程式,在進程中包含多個線程用於提高軟體運行速度。 在android網路請求中,我們知道在日常開發中不能在子線程中跟新ui,否則報錯Only the original thread that created a vi ...
  • 現如今, AR技術不斷發展,人們不再滿足於運用鍵盤、滑鼠等簡單器械來實現傳統的人機交互模式。隨著用戶接觸機器的多樣化,繁瑣的操作不但對一些用戶有門檻,而且還增加其學習成本;如果能用自然且符合日常生活習慣的人機交互模式,不僅更好上手,也能讓開發者們在應用內開發更多玩法。比如在視頻直播或者拍照過程中,一 ...
  • 對象中可以直接寫變數 ES6 允許在大括弧裡面,直接寫入變數和函數,作為對象的屬性和方法。 const foo = 'bar'; const obj = {foo}; //key值就是foo,value值是 foo變數對應的值 // 輸出的是 {foo: "bar"} console.log(obj ...
  • 這裡給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 現在 uniapp 開發的實時音視頻聊天類的 APP 大部分都要在 nvue 頁面上進行開發。雖然 nvue 與 vue 的區別不是很大,但還是有所差異的。 仔細查看了 uniapp 官網,發現了可以使用原生子窗體進行開發,可以把整個視頻 ...
  • 要成為一名優秀的 Web 開發人員,最快的方法就是練習。一個很好的練習方法是儘可能多地構建初學者項目。那是因為每個項目都會提出一個獨特的問題和解決方案,因此您解決的項目越多,您獲得的知識就越多。將您完成的每個項目都視為您獲得的獎牌。您擁有的獎牌越多,您就越能準備好應對下一個難度更大的項目。 為了幫助 ...
  • 個人名片: 對人間的熱愛與歌頌,可抵歲月冗長:sun_with_face: Github👨🏻‍💻:念舒_C.ying CSDN主頁✏️:念舒_C.ying 個人博客:earth_asia: :念舒_C.ying 預覽圖 直接進入我的網站吧 >> Z_C戀愛日記 下載源碼 鏈接:https:// ...
  • 在vue2中,提供了provide和inject配置,可以讓開發者在高層組件中註入數據,然後在後代組件中使用 除了相容vue2的配置式註入,vue3在composition api 中添加了provide和inject方法,可以在setup函數中註入 和使用數據 基本使用 provide('key' ...
  • 自定義 封裝單列模式! global state 由於vue3的響應式系統本身可以脫離組件而存在,因此可以充分利用這一點,輕鬆製造多個全局響應式數據, 並且通過和vuex一樣 通過某個模塊指定方法修改數據,不能直接修改數據,並且讓數據成為全局響應式 並且在代碼體積上絕對的輕量級!比市面上的任何第三方 ...
一周排行
    -Advertisement-
    Play Games
  • 1. 說明 /* Performs operations on System.String instances that contain file or directory path information. These operations are performed in a cross-pla ...
  • 視頻地址:【WebApi+Vue3從0到1搭建《許可權管理系統》系列視頻:搭建JWT系統鑒權-嗶哩嗶哩】 https://b23.tv/R6cOcDO qq群:801913255 一、在appsettings.json中設置鑒權屬性 /*jwt鑒權*/ "JwtSetting": { "Issuer" ...
  • 引言 集成測試可在包含應用支持基礎結構(如資料庫、文件系統和網路)的級別上確保應用組件功能正常。 ASP.NET Core 通過將單元測試框架與測試 Web 主機和記憶體中測試伺服器結合使用來支持集成測試。 簡介 集成測試與單元測試相比,能夠在更廣泛的級別上評估應用的組件,確認多個組件一起工作以生成預 ...
  • 在.NET Emit編程中,我們探討了運算操作指令的重要性和應用。這些指令包括各種數學運算、位操作和比較操作,能夠在動態生成的代碼中實現對數據的處理和操作。通過這些指令,開發人員可以靈活地進行算術運算、邏輯運算和比較操作,從而實現各種複雜的演算法和邏輯......本篇之後,將進入第七部分:實戰項目 ...
  • 前言 多表頭表格是一個常見的業務需求,然而WPF中卻沒有預設實現這個功能,得益於WPF強大的控制項模板設計,我們可以通過修改控制項模板的方式自己實現它。 一、需求分析 下圖為一個典型的統計表格,統計1-12月的數據。 此時我們有一個需求,需要將月份按季度劃分,以便能夠直觀地看到季度統計數據,以下為該需求 ...
  • 如何將 ASP.NET Core MVC 項目的視圖分離到另一個項目 在當下這個年代 SPA 已是主流,人們早已忘記了 MVC 以及 Razor 的故事。但是在某些場景下 SSR 還是有意想不到效果。比如某些靜態頁面,比如追求首屏載入速度的時候。最近在項目中回歸傳統效果還是不錯。 有的時候我們希望將 ...
  • System.AggregateException: 發生一個或多個錯誤。 > Microsoft.WebTools.Shared.Exceptions.WebToolsException: 生成失敗。檢查輸出視窗瞭解更多詳細信息。 內部異常堆棧跟蹤的結尾 > (內部異常 #0) Microsoft ...
  • 引言 在上一章節我們實戰了在Asp.Net Core中的項目實戰,這一章節講解一下如何測試Asp.Net Core的中間件。 TestServer 還記得我們在集成測試中提供的TestServer嗎? TestServer 是由 Microsoft.AspNetCore.TestHost 包提供的。 ...
  • 在發現結果為真的WHEN子句時,CASE表達式的真假值判斷會終止,剩餘的WHEN子句會被忽略: CASE WHEN col_1 IN ('a', 'b') THEN '第一' WHEN col_1 IN ('a') THEN '第二' ELSE '其他' END 註意: 統一各分支返回的數據類型. ...
  • 在C#編程世界中,語法的精妙之處往往體現在那些看似微小卻極具影響力的符號與結構之中。其中,“_ =” 這一組合突然出現還真不知道什麼意思。本文將深入剖析“_ =” 的含義、工作原理及其在實際編程中的廣泛應用,揭示其作為C#語法奇兵的重要角色。 一、下劃線 _:神秘的棄元符號 下劃線 _ 在C#中並非 ...