Spring security - 使用特定匹配器创建 2 个过滤器链

问题描述

我正在为现有的 Spring 项目实施 ADFS 支持。 由于我们已经拥有自己的 JWT 身份验证,我们希望与 ADFS 身份验证并行工作,因此我想实现一个新的过滤器链,该链将仅处理某些 API 请求路径。 我的意思是我想创建:

  • 将处理所有 /adfs/saml/** API 调用的 ADFS 过滤器链
  • 保留将处理所有其余 API 调用认过滤器链

我正在使用 ADFS spring security lib 定义过滤器链,如下所示:

public abstract class SAMLWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

//some code

 protected final HttpSecurity samlizedConfig(final HttpSecurity http) throws Exception {
        http.httpBasic().authenticationEntryPoint(samlEntryPoint())
                .and()
                .csrf().ignoringAntMatchers("/saml/**")
                .and()
                .authorizeRequests().antMatchers("/saml/**").permitAll()
                .and()
                .addFilterBefore(MetadataGeneratorFilter(),ChannelProcessingFilter.class)
                .addFilterafter(filterChainProxy(),BasicAuthenticationFilter.class);

        // store CSRF token in cookie
        if (samlConfigBean().getStoreCsrftokenInCookie()) {
            http.csrf()
                    .csrftokenRepository(csrftokenRepository())
                    .and()
                    .addFilterafter(new CsrfheaderFilter(),CsrfFilter.class);
        }

        return http;
    }
}

我扩展了这个类:

@EnableWebSecurity
@Configuration
@Order(15)
@requiredArgsConstructor
public class ADFSSecurityConfiguration extends SAMLWebSecurityConfigurerAdapter {
   @Override
    protected void configure(final HttpSecurity http) throws Exception {
        samlizedConfig(http)
                .authorizeRequests()
                .antMatchers("/adfs")
                .authenticated();
    }

}

但是在调试时我看到这个新的过滤器链被设置为匹配“任何”请求。 所以我可能把匹配器设置错了。

解决方法

实际上,在阅读official docs后,答案很简单: (请参阅“创建和自定义过滤器链”部分)

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        samlizedConfig(http)
                .antMatcher("/adfs/**");
    }

它不应该放在 .authorizeRequests() 之后,而应该放在第一个匹配器上。