簡體   English   中英

Spring Security-如何在CustomTokenAuthenticationFilter中指定過濾器處理url

[英]Spring Security- How to specify filter processing url in CustomTokenAuthenticationFilter

我正在嘗試使用令牌保護我的 Spring Rest API,這是我的自定義過濾器

public class CustomTokenAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    private static final Logger logger = LoggerFactory.getLogger(CustomTokenAuthenticationFilter.class);

    public CustomTokenAuthenticationFilter(String defaultFilterProcessesUrl) {
        super(defaultFilterProcessesUrl);
        super.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher(defaultFilterProcessesUrl));
        setAuthenticationManager(new NoOpAuthenticationManager());
        setAuthenticationSuccessHandler(new TokenSimpleUrlAuthenticationSuccessHandler());
    }


    public final String HEADER_SECURITY_TOKEN = "X-CustomToken"; 

    @Override 
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        String token = request.getHeader(HEADER_SECURITY_TOKEN);
        logger.info("token found:"+token);
        AbstractAuthenticationToken userAuthenticationToken = authUserByToken(token);
        if(userAuthenticationToken == null || userAuthenticationToken.getPrincipal().equals("guest")) throw new AuthenticationServiceException(MessageFormat.format("Error | {0}", "Bad Token"));
        return userAuthenticationToken;
    }


    /**
     * authenticate the user based on token
     * @return
     */
    private AbstractAuthenticationToken authUserByToken(String token) {
        if(token==null) {
            return null;
        }
        AbstractAuthenticationToken authToken = new MyToken(token);
        try {
            return authToken;
        } catch (Exception e) {
            logger.error("Authenticate user by token error: ", e);
        }
        return authToken;
    }


    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        super.doFilter(req, res, chain);
    }

}

這是我配置它的方式

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    protected AbstractAuthenticationProcessingFilter getFilter() {
        return new CustomTokenAuthenticationFilter("/api/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.addFilterBefore(getFilter(), UsernamePasswordAuthenticationFilter.class)
        .csrf().disable();
    }
}

如果你看一下getFilter(),我已經通過了“/api/*”作為過濾器處理url,但是我想用HttpSecurity對象配置這些url,一些如下

http.authorizeRequests().antMatchers("/", "/rome").permitAll()
            .antMatchers("/api/admin", "/api/newUser").access("hasRole('ADMIN')")
            .antMatchers("/api/db").access("hasRole('ADMIN') or hasRole('DBA')")

我看到的問題是,自定義過濾器需要一個字符串作為“過濾器處理 url”,但我不想指定任何內容。 該信息應該通過antMatchers等配置HttpSecurity對象來antMatchers

真的有可能嗎? 如果是,我怎么能做到這一點?

我使用了OncePerRequestFilter

public class MyAuthenticationFilter extends OncePerRequestFilter {

    // private RequestMatcher requestMatcher;
    private List<RequestMatcher> includedPathMatchers = new ArrayList<>();
    private List<RequestMatcher> excludedPathMatchers = new ArrayList<>();

    // implement getters and setters
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        // your filter implementation and security logics
    }

}

您可以將此類視為普通 bean(使用@Autowired等)。 然后你只需要在你的上下文中注冊它並將它注入到安全鏈中。

希望能幫助到你。

這個答案對你有用。 它說要使用 AbstractAuthenticationProcessingFilter 中可用的 setter setFilterProcessingURL()

暫無
暫無

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

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