簡體   English   中英

在Spring Security中的FORM_LOGIN_FILTER之后添加可選的身份驗證步驟

[英]Add optional authentication steps after FORM_LOGIN_FILTER in Spring Security

我在Web應用程序中具有使用Spring Security的基本登錄工作流程:用戶通過表單登錄,該表單最終由應用程序邏輯處理在UserDetailsService ,該邏輯從DaoAuthenticationProvider調用,並使用UsernamePasswordAuthenticationFilter創建的令牌。

但是,在某些情況下(通過用戶首選項在運行時確定),在此之后,我想再進行一次身份驗證步驟(基本上是兩因素身份驗證)。 我試過像這樣添加另一個過濾器

<custom-filter ref="twoFactorAuthFilter" after="FORM_LOGIN_FILTER"/>

但是如果表單登錄成功,則永遠不會調用此過濾器。 我的計划是創建一個特殊的TwoFactorAuthenticationToken能夠被接受TwoFactorAuthenticationProvider但不調用過濾器,我的新的認證供應商是不會。 如果登錄憑據錯誤,我希望整個安全鏈中止,但如果登錄憑據正確,則繼續遍歷它,然后繼續執行(可選)下一步。

是否可以不重寫現有的UsernamePasswordAuthenticationFilter來做我想做的事情? 我覺得這一定很容易,因為Spring通常是相當可擴展的,但是我已經為此奮斗了很多天,還沒有取得成功。

您要擁有兩個過濾器:一個用於userNamePasswordFilter ,另一個用於您的tokenFilter 如果您的用戶已啟用身份驗證雙因素,你userDetailsServicedaoAuthenticationProvider應該給予他的只有一個實例SimpleGrantedAuthority與角色“ROLE_PRE_AUTH”為例。 僅對具有此角色的用戶提供對tokenFilter的訪問權限-“ ROLE_PRE_AUTH”,並且該篩選器應嘗試對輔助令牌進行身份驗證,然后繼續從tokenProvider授予用戶其實際權限(USER,ADMIN等)。 再次顯示該彈出窗口的方法是檢查用戶的角色是否為“ ROLE_PRE_AUTH”。

您只需要擴展DaoAuthenticationProvider並使用登錄后身份驗證邏輯覆蓋additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication)

public CustomDaoAuthenticationProvider extends DaoAuthenticationProvider {

    public additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        super.additionalAuthenticationChecks(userDetails, authentication);

        // Your Logic Here
    }
}

編輯

可能是我誤解了您的問題,因為您提到了“邏輯”。 無論如何,這篇文章為您的問題提供了一個優雅的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM