javaspring-bootspring-security

Authentication with Spring Security


I have some confusion when working with authentication in spring security. There are two ways of authentication.

  1. By overriding configure method
  2. By implementing bean instance for AuthenticationProvider

I need to know what is the difference between them and the pros and cons of using each.

1.

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

@Bean
public BCryptPasswordEncoder getBCryptPasswordEncoder(){
    return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationProvider authenticationProvider(){
     DaoAuthenticationProvider daoAuthenticationProvider=new DaoAuthenticationProvider();
     daoAuthenticationProvider.setUserDetailsService(userDetailsService);
     daoAuthenticationProvider.setPasswordEncoder(new BCryptPasswordEncoder());
     return daoAuthenticationProvider;
}

Solution

  •     @Override
        protected void configure(AuthenticationManagerBuilder auth) {
            auth.authenticationProvider(authenticationProvider1())
                .authenticationProvider(authenticationProvider2());
        }
    
        @Bean("my-auth-provider-1")
        public AuthenticationProvider authenticationProvider1(){
            DaoAuthenticationProvider provider=new DaoAuthenticationProvider();
            provider.setUserDetailsService(userDetailsService());
            return provider;
        }
    
        @Bean("my-auth-provider-2")
        public AuthenticationProvider authenticationProvider2(){
            DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
            provider.setUserDetailsService(userDetailsService());
            return provider;
        }
      
    

    enter image description here

    Note

    I have simplified a bit here. Actually ProviderManager can have parent too. But effectively it has a list of providers. See https://spring.io/guides/topicals/spring-security-architecture

    enter image description here