spring-security 无法示例化[javax.servlet.Filter]:工厂方法'springSecurityFilterChain'无法在anyRequest之后配置antMatchers

gev0vcfq  于 2022-11-11  发布在  Spring
关注(0)|答案(2)|浏览(641)

我在将Sping Boot 版本升级到2.6.2后收到此错误:
Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalStateException: Can't configure antMatchers after anyRequest
这是我的securityConfig类从WebSecurityConfigurerAdapter扩展而来的。

@Override
protected void configure(HttpSecurity http) throws Exception {
    super.configure(http);
    http.csrf().disable().headers().frameOptions().disable().and().sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests().antMatchers("/api/**")
        .authenticated().and()
        .addFilterAfter(new TokenAuthenticationProcessingFilter(
            new PiAuthenticationProvider(
                new ApplicationPropertiesDataAdapterPi(this.applicationProperties)),
            "/api/**", null, new CustomAuthenticationFailureHandler(),
            AuthTokenUtil::extractXAuthorizationToken), BasicAuthenticationFilter.class);
}
bqujaahr

bqujaahr1#

当您调用super.configure(http)时,它实际上执行以下操作:

protected void configure(HttpSecurity http) throws Exception {
        this.logger.debug("Using default configure(HttpSecurity). "
                + "If subclassed this will potentially override subclass configure(HttpSecurity).");
        http.authorizeRequests((requests) -> requests.anyRequest().authenticated());
        http.formLogin();
        http.httpBasic();
    }

在此之后,您将尝试再次执行.authorizeRequests().antMatchers(“/api/**”),这将导致此错误。

gxwragnw

gxwragnw2#

在另一种情况下,您也会收到此错误无法示例化[javax.servlet.Filter]:工厂方法“springSecurityFilterChain”引发异常
引发此异常的代码

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .authorizeRequests().antMatchers("/authenticate").permitAll()
            .anyRequest();
}

修复:附加**.authenticated()**方法

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .authorizeRequests().antMatchers("/authenticate").permitAll()
            .anyRequest().authenticated();
}

相关问题