在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
  • 前言 JSON Web Token(JWT)是一個非常輕巧的規範。這個規範允許我們使用 JWT 在用戶和伺服器之間傳遞安全可靠的信息。一個 JWT 實際上就是一個字元串,它由三部分組成,頭部、載荷與簽名。前兩部分需要經過 Base64 編碼,後一部分通過前兩部分 Base64 編碼後再加密而成。針對 ...
  • 一:背景 1. 講故事 今天本來想寫一篇 非托管泄露 的生產事故分析,但想著昨天就上了一篇非托管文章,連著寫也沒什麼意思,換個口味吧,剛好前些天有位朋友也找到我,說他們的拍攝監控軟體卡死了,讓我幫忙分析下為什麼會卡死,聽到這種軟體,讓我不禁想起了前些天 在程式員桌子上安裝監控 的新聞,參考如下: 我 ...
  • 文章目錄 介紹 ABP的依賴註入系統是基於Microsoft的依賴註入擴展庫(Microsoft.Extensions.DependencyInjection nuget包)開發的。所以我們採用dotnet自帶的註入方式也是支持的。 由於ABP是一個模塊化框架,因此每個模塊都定義它自己的服務併在它自 ...
  • 前言 外觀模式,英文名稱是:Facade Pattern。我們先從名字上來理解一下“外觀模式”。我看到了“外觀”這個詞語,就想到了“外表”這個詞語,兩者有著很相近的意思。就拿談戀愛來說,“外表”很重要,如果第一眼看著很舒服、有眼緣,那就有交往下去的可能。如果長的“三寸釘、枯樹皮”,估計就夠嗆了。在這 ...
  • 模擬.NET實際應用場景,綜合應用三個主要知識點:一是使用dnSpy反編譯第三庫及調試,二是使用Lib.Harmony庫實現第三庫攔截、偽造,三是實現同一個庫支持多版本同時引用。 ...
  • 通過strimzi部署的kafka集群,如何部署prometheus+grafana去監控呢?官方文檔信息量太大,即便照著做也可能失敗,這裡有一份詳細的保姆級操作指南,助您成功部署監控服務 ...
  • 在工具類中封裝getBean,使用哪個介面來實現 實事上,在工具類中,實現BeanFactoryPostProcessor和ApplicationContextAware介面後,使用它們構造方法里的對象ConfigurableListableBeanFactory和ApplicationContex ...
  • 1章:系統基礎信息模塊詳解 通過第三方模塊獲取伺服器的基本性能、塊設備、網卡介面、網路地址庫等信息。 1.1 系統性能模塊psutil:獲取系統性能信息、記憶體信息、磁碟信息、網路信息、用戶信息等。 1.2 IP地址處理模塊IPy: 處理IP地址,網段等。 1.3 DNS處理模塊dnspython: ...
  • EasyExcel動態表頭導出(支持多級表頭) 在很多業務場景中,都會應用到動態表頭的導出,也會涉及到多級表頭的導出,如下圖所示 通過EasyExcel,我們可以快速實現這一需求,具體代碼如下 DynamicHeader import java.util.List; /** *@Author: <a ...
  • 基於java線上婚紗定製系統設計與實現,可適用於線上婚紗攝影預定系統,基於web的婚紗影樓管理系統設計,基於web的婚紗影樓管理系統設計,婚紗攝影網系統,婚紗攝影網站系統,婚紗攝影網站系統,婚紗系統,婚紗管理系統等等; ...