Search code examples
spring-security

How to add an additional AuthenticationProvider without using WebSecurityConfigurerAdapter


Prior to Spring Security 5.7 it was possible to add additional AuthenticationProviders to the global AuthenticationManager this way:

public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 

    ...

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(customAuthenticationProvider);
    }

}

With Spring Security 5.7 the WebSecurityConfigurerAdapter was deprecated.

Question: ho should i migrate this code to solve the deprecation?

When i try to register the additional AuthenticationProvider as @Bean, the autocreated authentication provider for username/password based authentication gets replaced, leading to

No AuthenticationProvider found for org.springframework.security.authentication.UsernamePasswordAuthenticationToken

I read the blog post https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter but found no hints about adding additional authentication providers to the global AuthenticationManager.


Solution

  • If you have a single AuthenticationProvider you can register it as a bean and it will be picked up by Spring Security:

    @Bean
    public CustomAuthenticationProvider customAuthenticationProvider() {
        return new CustomAuthenticationProvider();
    }
    

    Alternatively, you can add additional AuthenticationProviders in the HttpSecurity configuration:

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            // ...
            .authenticationProvider(new CustomAuthenticationProvider());
        return http.build();
    }