Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 360
Eric B. Avatar asked Mar 21 '18 15:03

Eric B.


1 Answers

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.

like image 76
shazin Avatar answered Oct 04 '22 14:10

shazin