Issue
In my application there are two authentication options that take effect depending on the path. All endpoints under the API path are authenticated via a simple token. All others via OAuth2.
In the past, I had two classes that both extended the WebSecurityConfigurerAdapter. Shortened versions of the classes similar to https://stackoverflow.com/a/60283968 :
@Configuration
@EnableWebSecurity
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ApiEndpointConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.requestMatchers().antMatchers(API + "/**")
.and()
// authentication for token based authentication
.authenticationProvider(tokenAuthProvider)
.addFilterBefore(tokenAuthFilter, BasicAuthenticationFilter.class);
}
}
@Configuration
@EnableWebSecurity
public class OAuth2EndpointConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http // all non api requests handled here
.oauth2Login()
.tokenEndpoint().accessTokenResponseClient(oAuth2AccessTokenResponseClient())
.and()
.userInfoEndpoint().userService(oAuth2UserService());
}
}
In Spring Security 5.7.0-M2 the WebSecurityConfigurerAdapter
has been deprecated. Therefore I would like to replace this configuration now with a component-based configuration. As recommended here: https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter . This is the point at which I currently fail.
Simply replacing the existing methods with configuration beans of the SecurityFilterChain leads to duplicates.
@Bean
protected SecurityFilterChain configure(HttpSecurity http) throws Exception {
return http [...] .build();
}
The bean 'configure' [...] could not be registered. A bean with that name has already been defined [...]
By changing the annotations, I have only managed, at best, to have one configuration take effect. I can't merge the configurations because they have very different strategies. How would I configure two different filters by path after the deprecation of the adapter?
Solution
You don't have to keep the same method name "configure" for both the beans. Any custom method name is allowed, the return type "SecurityFilterChain" needs to be same. Please refer https://docs.spring.io/spring-security/reference/5.7.0-M2/servlet/configuration/java.html#_multiple_httpsecurity
Answered By - Noble
Answer Checked By - Senaida (JavaFixing Volunteer)