spring引导http安全配置匿名筛选器和另一路径上的自定义筛选器

qoefvg9y  于 2021-08-25  发布在  Java
关注(0)|答案(2)|浏览(172)

我在尝试使用WebSecurityConfigureAdapter配置http安全性时遇到了一个奇怪的问题。以下是我迄今为止尝试的完整配置类:

@Slf4j
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
@ConditionalOnProperty(name = "module.client.security.enabled")
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Value("${management.endpoints.web.base-path}")
  private String managementEndpoint;

  @Autowired
  private List<ModuleProperties> moduleProperties;

  @Override
  public void configure(WebSecurity web) {
    web.ignoring()
        .antMatchers(this.managementEndpoint + "/**");
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.httpBasic().disable();
    http.formLogin().disable();
    // FIXME also doesn't work because of the later http.requestMatchers().antMatchers() calls
    http.authorizeRequests()
        .antMatchers("/**").anonymous();

    http.requestMatchers()
        .antMatchers("/app/**")
        .and()
        .addFilterBefore(new ClientResolveFilter(), FilterSecurityInterceptor.class);

  }

我想做的实际上是为所有端点启用匿名身份验证,以防止在securitycontextholder上操作时出现NullPointerException,另外,只为一个子集或不同的端点路径启用/添加自定义筛选器,这是 /app/** 在这种情况下。
我原以为上面的代码可以工作,但实际发生的情况是,所有人都禁用了匿名身份验证筛选器,而这两个筛选器只对路径有效 /app/** 只有
如果我移除 http.requestMatchers().antMatchers("/app/**") 部分,然后anonymousauthenticationfilter将正常用于所有路径。我怀疑第二个 .antMatchers("/app/**") call有点取代了前一个,或者隐式地替代了它,这对我来说没有意义,但我可能错了。
我试着深入到源代码中,但仍然感到困惑,无法找到一个干净的解决方案,使它如我所期望的那样工作。任何想法和帮助都将不胜感激。
干杯
编辑:我使用的是SpringBoot2.5.2,SpringSecurity版本是5.5.1

hmtdttj4

hmtdttj41#

这个 addFilterBefore (和其他addfilter*)方法将过滤器添加到适用于所有请求的过滤器链中。如果希望筛选器仅应用于某些请求,则必须检查筛选器内部(例如使用 HttpServletRequest.getgetRequestURI() 检查url)。

ecbunoof

ecbunoof2#

在@dickson的建议下,我发现了一种特殊的bean,叫做 FilterRegistrationBean 由Spring Boot提供。
因此,我将其配置为一个bean,它只对配置的路径应用特定的servlet过滤器:

@Bean
public FilterRegistrationBean<ClientResolveFilter> clientResolveFilter(){
  final FilterRegistrationBean<ClientResolveFilter> frb = new FilterRegistrationBean<>();
  frb.setFilter(new ClientResolveFilter());
  frb.addUrlPatterns("/app/*");
  return frb;
}

这个解决方案完全符合我的要求。
请注意,路径字符串现在不是ant匹配器-必须使用single编写 /app/* 而不是双倍 /app/** -这实际上是我们手动配置web.xml文件时的模式,就像以前一样:)

相关问题