在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
  • .Net8.0 Blazor Hybird 桌面端 (WPF/Winform) 實測可以完整運行在 win7sp1/win10/win11. 如果用其他工具打包,還可以運行在mac/linux下, 傳送門BlazorHybrid 發佈為無依賴包方式 安裝 WebView2Runtime 1.57 M ...
  • 目錄前言PostgreSql安裝測試額外Nuget安裝Person.cs模擬運行Navicate連postgresql解決方案Garnet為什麼要選擇Garnet而不是RedisRedis不再開源Windows版的Redis是由微軟維護的Windows Redis版本老舊,後續可能不再更新Garne ...
  • C#TMS系統代碼-聯表報表學習 領導被裁了之後很快就有人上任了,幾乎是無縫銜接,很難讓我不想到這早就決定好了。我的職責沒有任何變化。感受下來這個系統封裝程度很高,我只要會調用方法就行。這個系統交付之後不會有太多問題,更多應該是做小需求,有大的開發任務應該也是第二期的事,嗯?怎麼感覺我變成運維了?而 ...
  • 我在隨筆《EAV模型(實體-屬性-值)的設計和低代碼的處理方案(1)》中介紹了一些基本的EAV模型設計知識和基於Winform場景下低代碼(或者說無代碼)的一些實現思路,在本篇隨筆中,我們來分析一下這種針對通用業務,且只需定義就能構建業務模塊存儲和界面的解決方案,其中的數據查詢處理的操作。 ...
  • 對某個遠程伺服器啟用和設置NTP服務(Windows系統) 打開註冊表 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer 將 Enabled 的值設置為 1,這將啟用NTP伺服器功 ...
  • title: Django信號與擴展:深入理解與實踐 date: 2024/5/15 22:40:52 updated: 2024/5/15 22:40:52 categories: 後端開發 tags: Django 信號 松耦合 觀察者 擴展 安全 性能 第一部分:Django信號基礎 Djan ...
  • 使用xadmin2遇到的問題&解決 環境配置: 使用的模塊版本: 關聯的包 Django 3.2.15 mysqlclient 2.2.4 xadmin 2.0.1 django-crispy-forms >= 1.6.0 django-import-export >= 0.5.1 django-r ...
  • 今天我打算整點兒不一樣的內容,通過之前學習的TransformerMap和LazyMap鏈,想搞點不一樣的,所以我關註了另外一條鏈DefaultedMap鏈,主要調用鏈為: 調用鏈詳細描述: ObjectInputStream.readObject() DefaultedMap.readObject ...
  • 後端應用級開發者該如何擁抱 AI GC?就是在這樣的一個大的浪潮下,我們的傳統的應用級開發者。我們該如何選擇職業或者是如何去快速轉型,跟上這樣的一個行業的一個浪潮? 0 AI金字塔模型 越往上它的整個難度就是職業機會也好,或者說是整個的這個運作也好,它的難度會越大,然後越往下機會就會越多,所以這是一 ...
  • @Autowired是Spring框架提供的註解,@Resource是Java EE 5規範提供的註解。 @Autowired預設按照類型自動裝配,而@Resource預設按照名稱自動裝配。 @Autowired支持@Qualifier註解來指定裝配哪一個具有相同類型的bean,而@Resourc... ...