Home > Enterprise >  Spring Security: DaoAuthenticationProvider autoconfiguration with default PasswordEncoder and UserDe
Spring Security: DaoAuthenticationProvider autoconfiguration with default PasswordEncoder and UserDe

Time:01-26

I'm using Spring Security.

I defined the following bean for PasswordEncoder:

  @Bean
  public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }

And also I have this class implementing UserDetailsService:

@Service
public class UserService implements UserDetailsService { //... }

Then I defined the following bean:

  @Bean
  public DaoAuthenticationProvider authenticationProvider(UserDetailsService userDetailsService,
      PasswordEncoder passwordEncoder) {
    DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
    authProvider.setUserDetailsService(userDetailsService);
    authProvider.setPasswordEncoder(passwordEncoder);
    return authProvider;
  }

I'm not doing much in the later bean definition since it is just creating a DaoAuthenticationProvider with default PasswordEncoder and UserDetailsService beans.

My question is if there is someway to avoid the trivial definition of DaoAuthenticationProvider or if it is always necessary.

Thanks!

UPDATE:

I forgot to mention that I'm using Basic Auth (it's a very simple use case):

  @Bean
  public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
    return http.build();
  }

CodePudding user response:

Based on your security configuration (from the updated question), Spring Security will create an AuthenticationManager composed with a DaoAuthenticationProvider configured more or less exactly like your @Bean. In most cases, you do not need to specify the @Bean DaoAuthenticationProvider, and it can be removed.

In other words, yes, you can avoid the definition of the AuthenticationProvider by specifying the SecurityFilterChain @Bean exactly as you have done.

You would typically only expose an AuthenticationProvider or (more commonly) an AuthenticationManager defined like your example if you require the use of that component in your own application code (e.g. in a @RestController or an @Service). Normally, Spring Security will automatically use the internally built AuthenticationManager in the BasicAuthenticationFilter on your behalf.

  • Related