繁体   English   中英

Spring security中为不同的antMachers添加不同的过滤器

[英]Adding different filters to different antMachers in Spring security

我正在尝试在春季启用 WebSecurity。 我实际上有两个端点(一个 GET 和一个 POST),我想为每个请求使用不同的GenericFilterBean

我已经尝试了下面的代码,但我无法获得所需的行为。 对于每个请求(GET 和 POST),都会调用两个过滤器(GetUserIdByToken 和 AuthUserIdTransactionId)。 你们能给我提供一种解决方案吗? 每个请求只有一个过滤器。 提前致谢。

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurity extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()       
        .requestMatchers()
           .antMatchers(HttpMethod.GET, "/me/accounts/{accountId}/transactions")
           .and()
           .addFilterBefore(new GetUserIdByToken(), BasicAuthenticationFilter.class)
        .requestMatchers()
            .antMatchers(HttpMethod.POST, "/me/accounts/{accountId/transactions/{transactionId}")
            .and()
            .addFilterBefore(new AuthUserIdTransactionId(), BasicAuthenticationFilter.class);

    }
}

每当您配置HttpSecurity ,您就是在配置FilterChain最终会出现的内容。 这意味着如果调用过滤器链,则将调用您添加到HttpSecurity每个过滤器。

方法一

如果您想有选择地“关闭” FilterChain某些过滤器,您可以将它们配置为这样做:

public class GetUserIdByToken extends GenericFilterBean {
    private AntPathRequestMatcher requestMatcher;

    public GetUserIdByToken(String path, HttpMethod method) {
        this.requestMatcher = new AntPathRequestMatcher(path, method);
    }

    // ...
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
       throws IOException, ServletException {
        
       if(!this.requestMatcher.matches(req) {
           chain.doFilter(req,resp);
           return;
       }

       // filter logic goes here...
    }
}

您可以对AuthUserIdTransactionId执行相同的操作。 然后只需将适当的路径和 http 方法传递给每个构造函数,并将两个过滤器添加到HttpSecurity

方法二

另一方面,如果您想要一个完全独立的FilterChain ,则必须配置两个WebSecurityConfigurerAdapter 这篇博文解释了如何做得很好。 或者你可以查看官方文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM