Issue
I get this error after upgrading spring boot version to 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
This is my securityConfig class extends fromn 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);
}
Solution
When you call super.configure(http) it actually does the following:
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();
}
And after that you are trying to execute .authorizeRequests().antMatchers("/api/**") once again which causes this error. So simply don't call super.configure(http) and implement all logic you need in your method
Answered By - Andrey Grigoriev
Answer Checked By - Clifford M. (JavaFixing Volunteer)