ali-bouali / spring-boot-3-jwt-security

Sample project on how to implement JWT security based using Spring boot 3 and Spring security 6
https://aliboucoding.com/p/securing-your-spring-boot-3-0-applications-with-json-web-tokens-jwt
Apache License 2.0
1.86k stars 870 forks source link

Spring security warning - Global AuthenticationManager configured with an AuthenticationProvider bean #77

Closed theapplegeek closed 2 months ago

theapplegeek commented 3 months ago

Hi, I'm using spring 3.3.1 and when run application it show this warning:

WARN 31306 --- [main] r$InitializeUserDetailsManagerConfigurer : Global AuthenticationManager configured with an AuthenticationProvider bean. UserDetailsService beans will not be used for username/password login. Consider removing the AuthenticationProvider bean. Alternatively, consider using the UserDetailsService in a manually instantiated DaoAuthenticationProvider.

How I can fix this? Thx.

JBraddockm commented 3 months ago

Remove AuthenticationManager bean from ApplicationConfig. It is my understanding that setting AuthenticationManager like this is not recommended.

 @Bean
  public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
    return config.getAuthenticationManager();
  }

Remove .authenticationProvider(authenticationProvider) from SecurityFilterChain in SecurityConfiguration.

Now refactor AuthenticationProvider bean in ApplicationConfig as follows:

@Bean
  public AuthenticationManager authenticationManager() {
    DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
    authProvider.setUserDetailsService(userDetailsService());
    authProvider.setPasswordEncoder(passwordEncoder());
    return new ProviderManager(authProvider);
  }

You should now see Global AuthenticationManager configured with UserDetailsService bean with name userDetailsService in the log.

theapplegeek commented 2 months ago

It works, thanks.

ApplicationConfig.java should be like:

@Configuration
@AllArgsConstructor
public class AuthenticationConfig {
  private final UserRepository repository;

  @Bean
  public UserDetailsService userDetailsService() {
    return username ->
        repository
            .findByUsername(username)
            .orElseThrow(() -> new UsernameNotFoundException("User not found"));
  }

  @Bean
  public AuthenticationManager authenticationManager() {
    DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
    authProvider.setUserDetailsService(userDetailsService());
    authProvider.setPasswordEncoder(passwordEncoder());
    return new ProviderManager(authProvider);
  }

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