Eric B.
Eric B.

Reputation: 24451

How to get the AuthenticationManager when using the AuthenticationManagerBuilder to add custom provider?

I'm using Spring Boot 2.0 (leveraging Spring Security 5.0). I'm trying to add a custom AuthenticationProvider to the AuthenticationManager in my WebSecurityConfigurerAdapter subclass. If I override the configure(AuthenticationManagerBuilder) method to supply my new provider, then I do not know how to retrieve the AuthenticationManager as a bean.

Ex:

public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception 
    {
        auth.authenticationProvider(customAuthenticationProvider);
    }
}

where customAuthenticationProvider implements AuthenticationProvider.

In the Spring docs, it seems to specify that the two are incompatible:

5.8.4 AuthenticationProvider You can define custom authentication by exposing a custom AuthenticationProvider as a bean. For example, the following will customize authentication assuming that SpringAuthenticationProvider implements AuthenticationProvider:

[Note] This is only used if the AuthenticationManagerBuilder has not been populated

Indeed, if I try to retrieve the AuthenticationManager bean using:

@Bean
public AuthenticationManager authenticationManager() throws Exception {
    return super.authenticationManagerBean();
}

then the configure() method is never even called.

So how can I add my own custom provider to the default list of providers, and still be able to retrieve the AuthenticationManager?

Upvotes: 5

Views: 7791

Answers (1)

shazin
shazin

Reputation: 21903

You can just override WebSecurityConfigurerAdapter.authenticationManagerBean() method and annotate it with @Bean annotation

 @Bean
 @Override
 public AuthenticationManager authenticationManagerBean() throws Exception {
     return super.authenticationManagerBean();
 }

And there is no Spring Boot 5.0, The latest release is Spring Boot 2.0. I believe you are talking about Spring Security 5.0.

Upvotes: 9

Related Questions