Multiple Spring Security filters

旧街凉风 提交于 2021-02-19 07:32:12

问题


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?

Filter 1 config:

@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);
}

Filter 2 config:

@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);
}

回答1:


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

Something like the following

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);

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.



来源:https://stackoverflow.com/questions/53238234/multiple-spring-security-filters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!