簡體   English   中英

如何不在過濾器鏈中使用 UsernamePasswordAuthenticationFilter?

[英]How not to use UsernamePasswordAuthenticationFilter in Filter Chain?

我正在開發一個 spring 啟動應用程序,我正在添加自定義過濾器並添加方法 addFilterBefore。

這是我的配置配置方法:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.cors().and().authorizeRequests()
                .anyRequest().authenticated();
        http.addFilterBefore(btoBSecurityFilter,UsernamePasswordAuthenticationFilter.class);

        http.httpBasic();
    }

這是我的自定義過濾器:

@Component
public class BtoBSecurityFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
       //I dont want to use this as I dont want to use UsernamePasswordAuthenticationFilter.  
        SecurityContextHolder.getContext().setAuthentication(getAuthentication(7312L,"tokenlelo"));
        filterChain.doFilter(httpServletRequest,httpServletResponse);
        logger.info("hey aaya");
    }

    // dont want to use this.
    public Authentication getAuthentication(Long userId, String token) {
        UserDetails userDetails = org.springframework.security.core.userdetails.User
                .withUsername("")
                .password("")
                .build();
        return new UsernamePasswordAuthenticationToken("", "", userDetails.getAuthorities());
    }

}

現在上面的代碼有效,但我不希望 UsernamePasswordAuthenticationFilter 在我的情況下發生,我只希望我的 customFilter 過濾掉對我的請求。

我怎樣才能做到這一點? 我無法使用addFilter方法,因為它會給出訂單錯誤。 我只希望我的自定義過濾器運行並且不希望 SecurityContext 設置或保存任何內容。

有人可以幫我弄這個嗎?

使用UsernamePasswordAuthenticationToken並不能保證UsernamePasswordAuthenticationFilter會過濾您的請求。

如果您查看源代碼(使用您的 IDEA 或 github),尤其是AbstractAuthenticationProcessingFilter方法boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response)UsernamePasswordAuthenticationFilter構造函數,您會看到UsernamePasswordAuthenticationFilter僅過濾與身份驗證請求匹配的請求(默認為對“/login”的 POST 請求)。

當您在UsernamePasswordAuthenticationFilter之前設置自定義過濾器時,無論如何都會在您的自定義過濾器之后調用此過濾器,除非您在自定義過濾器代碼中跳過filterChain.doFilter(httpServletRequest,httpServletResponse)方法。
但是,正如我之前所說,這並不意味着UsernamePasswordAuthenticationFilter會過濾您的請求。

因此,它不依賴於使用UsernamePasswordAuthenticationToken

UsernamePasswordAuthenticationToken只是Authentication的實現之一,可以在您的情況下使用。 當您將此 class 的公共構造函數與GrantedAuthority集合一起使用時,您將創建一個受信任的(即 isAuthenticated() = true)身份驗證令牌。 因此安全上下文將知道該請求已經過身份驗證。

順便說一句,您使用的構造函數只能由AuthenticationManagerAuthenticationProvider調用 - 這在javadoc中有說明。 為了安全使用,請嘗試static 工廠方法

return UsernamePasswordAuthenticationToken.authenticated(principal, credentials, userDetails.getAuthorities());

暫無
暫無

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

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