簡體   English   中英

帶有路徑變量的 Spring Boot AuthenticationToken

[英]Spring Boot AuthenticationToken with path variable

我有一個帶有自定義AuthenticationManagerPreAuthenticatedProcessingFilter ,我在其中進行身份驗證並創建AuthenticationToken 我現在需要訪問一個路徑變量(例如“/foo/{id}”的id)並將其用於我的身份驗證。 我如何訪問變量? 如果我使用.antMatchers("/foo/{id}").access("@demo.check(authentication,#id)"); 例如,我無法創建自己的令牌。

我目前的代碼是:

    MyAuthFilter filter = MyAuthFilter();
    filter.setAuthenticationManager(new AuthenticationManager() {

        @Override
        public Authentication authenticate(Authentication authentication) throws AuthenticationException {
            // ... authentication stuff
            // here i want to access the path variable
            return new MyAuthenticationToken(foo);
        }
    });
    httpSecurity.antMatcher("/foo/**").csrf().disable().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and().addFilter(filter).authorizeRequests().anyRequest().authenticated();

更新

我現在正在檢查訪問表達式中的所有內容(您可以在那里訪問 HttpServletRequest 並將路徑變量作為參數)。 我不想在控制器中有邏輯或檢查原始路徑。 所以現在這對我來說很好用:

httpSecurity.antMatcher("/foo/**").csrf().disable().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
            .antMatchers("/foo/test/{testId}/**")
            .access("@fooApiGuard.check(authentication, #testId)");

@Service
public class FooApiGuard {

    @Autowired
    private HttpServletRequest request;

    public boolean check(Authentication authentication, Long testId) throws AuthenticationException {
        // check stuff
        return true;
    }
}

Spring Security 是作為一個過濾器鏈構建的,這意味着在您的自定義過濾器或AuthenticationManager內部,您沒有與控制器方法本身內部完全相同的上下文。 事實上,您的自定義過濾器應該增加您的控制器將使用的上下文。

您可以訪問的是ServletRequestServletResponse對象,因此如果必須,您可以從中提取原始路徑。 然而,這並沒有給你很好地分離出來的請求參數。

如果路徑參數僅用於確定某人是否獲得授權,那么您可以簡化您的身份驗證邏輯,然后通過額外的安全檢查來增強您的控制器,以驗證例如域級別的安全問題(資源是否屬於當前用戶)。

暫無
暫無

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

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