0
votes

So I am studying Spring Security for a implementation. I came across a piece of code I cannot get my head around. So as per documentation the following method needs to be overridden when we want to customize the AuthenticationManager used by Spring.

protected void configure(AuthenticationManagerBuilder auth) throws java.lang.Exception

My question is who is calling this method and passing the AuthenticationManagerBuilder instance here. The working examples I see do not create/expose any AuthenticationManagerBuilder bean.

Also , i see the following in the documentation,

protected AuthenticationManager authenticationManager() throws java.lang.Exception Gets the AuthenticationManager to use.

The default strategy is if configure(AuthenticationManagerBuilder) method is overridden to use the AuthenticationManagerBuilder that was passed in. Otherwise, autowire the AuthenticationManager by type.

The overridden method is a void method and probably that is why I am getting confused more w.r.t what it is doing/should be doing.

Any help/pointers are highly appreciated. I know it works I just cant seem to figure out how. Much thanks.

1

1 Answers

2
votes

Assuming following is the code you came across

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(MyAuthenticationProvider);
    }
}

Note that

  1. The WebSecurityConfigurerAdapter provides a convenient base class for creating a WebSecurityConfigurer instance.
  2. The WebSecurityConfigurerAdapter implementation is a Configuration as it is annotated with @EnableWebSecurity

Here

@EnableWebSecurity is meta-annotated with @EnableGlobalAuthentication

@Retention(value=RUNTIME)
 @Target(value=TYPE)
 @Documented
 @Import(value={WebSecurityConfiguration.class,org.springframework.security.config.annotation.web.configuration.SpringWebMvcImportSelector.class,org.springframework.security.config.annotation.web.configuration.OAuth2ImportSelector.class})
 @EnableGlobalAuthentication
 @Configuration
public @interface EnableWebSecurity

and @EnableGlobalAuthentication imports AuthenticationConfiguration

@Retention(value=RUNTIME)
 @Target(value=TYPE)
 @Documented
 @Import(value=AuthenticationConfiguration.class)
 @Configuration
public @interface EnableGlobalAuthentication

AuthenticationConfiguration has the following piece of code that registers AuthenticationManagerBuilder as a bean

@Bean
public AuthenticationManagerBuilder authenticationManagerBuilder(
            ObjectPostProcessor<Object> objectPostProcessor, ApplicationContext context) {
        ...
    }