多个 Spring Security 过滤器 [英] Multiple Spring Security filters

查看:55
本文介绍了多个 Spring Security 过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个 Spring Security WebSecurityConfigurerAdapter 配置.我想用过滤器 1 过滤到路径 /filter1 的所有请求,不包括 /filter1/filter2 路径.后一个我想用过滤器2过滤.我该如何实现?

I have 2 Spring Security WebSecurityConfigurerAdapter configs. I want to filter all requests to path /filter1 with filter 1, excluding /filter1/filter2 path. The latter one I want to filter with filter 2. How can I achieve it?

过滤器 1 配置:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf().disable()
        .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
        .authorizeRequests()
            .antMatchers("filter1/filter2/**").permitAll()
            .and()
        .antMatcher("filter1/**")
        .authorizeRequests()
            .anyRequest().authenticated()
            .and()
        .addFilterBefore(filter1, FilterSecurityInterceptor.class);
}

过滤器 2 配置:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf().disable()
        .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
        .antMatcher("filter1/filter2/**")
        .authorizeRequests()
            .anyRequest().authenticated()
            .and()
        .addFilterBefore(filter2, FilterSecurityInterceptor.class);
}

推荐答案

只需编写一个配置,按照它们应该匹配的方式对 url 进行排序(排序在这里很重要!).

Just write a single configuration, ordering the urls in the way they should match (ordering is important here!).

类似于以下内容

http
  .csrf().disable()
  .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
  .and()
        .authorizeRequests().anyRequest().authenticated()
   .and()
        .antMatcher("filter1/filter2/**")
        .addFilterBefore(filter2, FilterSecurityInterceptor.class)
        .antMatcher("filter1/**")
        .addFilterBefore(filter1, FilterSecurityInterceptor.class);

应该这样做.它将匹配最具体的一个并使用该过滤器链.不确定是否需要将 .authorizeRequests().anyRequest().authenticated() 也移动到每个映射.

Should do that. It will match the most specific one and use that filter chain. Not sure if you need to move the .authorizeRequests().anyRequest().authenticated() to each mapping as well.

这篇关于多个 Spring Security 过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆