Home > OS >  Make DaoAuthenticationProvider Work with the AuthenticationManager after WebSecurityConfigurerAdapte
Make DaoAuthenticationProvider Work with the AuthenticationManager after WebSecurityConfigurerAdapte

Time:09-07

I am creating a complete user login and registration Backend system with Email Verification and usage of PostgreSQL to store the user's credentials. I've come to a point where I am having problems at the security layer. To be more specific I am having the following code which since WebSecurityConfigurerAdapter deprecation, I want to change:

OLD VERSION BEFORE DEPRECATION

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

    @Bean
    public DaoAuthenticationProvider daoAuthenticationProvider() {
        DaoAuthenticationProvider provider =
                new DaoAuthenticationProvider();
        provider.setPasswordEncoder(bCryptPasswordEncoder);
        provider.setUserDetailsService(applicationUserService);
        return provider;
    }

I've searched this question and found that AuthenticationManagerBuilder can now be accessed as follows:

NEWEST VERSION OF AUTHENTICATION MANAGER

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

My problem is that I can't find a way to inject my daoAuthenticationProvider to the newest method of AuthenticationManager. Any proposals???

CodePudding user response:

Adding a custom authentication provider is configured in the SecurityFilterChain bean. Although looking at the given code, standard DAO authentication would automatically be added with http.formLogin() without the need for an AuthenticationProvider.

@Bean
public SecurityFilterChain filterChain(DaoAuthenticationProvider daoAuthenticationProvider) throws Exception
{
    http.authenticationProvider(daoAuthenticationProvider);
    return http.build();
}

See also https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter

CodePudding user response:

You should not need the AuthenticationConfiguration for that, you could just create your own bean, like so:

@Bean
public AuthenticationManager authenticationManager(PasswordEncoder passwordEncoder, UserDetailsService userDetailsService) {
    DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
    provider.setPasswordEncoder(passwordEncoder);
    provider.setUserDetailsService(userDetailsService);
    return new ProviderManager(provider);
}
  • Related