Search code examples
springspring-bootspring-mvcspring-securityspring-data-jpa

Error creating and injecting BCryptPasswordEncoder in a service class


I want to hash and store the password in the database. When I try to inject the PasswordEncoder bean into my service class, I get the error mentioned below.

This is my first project using the Spring-security module and would appreciate your advice.

Spring Boot version:2.2.6.RELEASE

**SecurityConfiguration.java: security configuration class*

 @EnableWebSecurity
    @Configuration
    @ComponentScan(basePackages = { "com.sd.authandauthorizationbackendapp.security" })
    public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsService userDetailsService;

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        auth.parentAuthenticationManager(authenticationManagerBean())
                .userDetailsService(userDetailsService).
                .and().authenticationProvider(authProvider());
    }

    @Bean
    public DaoAuthenticationProvider authProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userDetailsService);
        authProvider.setPasswordEncoder(passwordEncoder());
        return authProvider;
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().and().csrf().disable().authorizeRequests()
                .antMatchers("/admin").hasRole("ADMIN")
                .antMatchers("/test").hasRole("USER")
                .antMatchers("/register").permitAll()
                .antMatchers("/").permitAll()
                .and().formLogin();
    }
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder(10, new SecureRandom());
    }
    }

UserServiceImpl.java: a service class to save user

 @Service
    public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    PasswordEncoder bCryptPasswordEncoder;

    @Override
    public void save(User user) {
        user.setPassword(bCryptPasswordEncoder.
                                  encode(user.getPassword()));
        user.setRoles(user.getRoles());
        userRepository.save(user);
    }
    }

ERROR

Unsatisfied dependency expressed through field 'bCryptPasswordEncoder';   Error creating 
bean with name 'passwordEncoder': Requested bean is currently in creation: Is there an 
unresolvable circular reference?

Please let me know if further code and details are needed.


Solution

  • Unless you use @Qualified("passwordEncoder") in the service class then spring will look for bCryptPasswordEncoder as bean. At the moment you are looking for a bean called bCryptPasswordEncoder.

    Change it to

      @Autowired
      PasswordEncoder passwordEncoder;
    

    or

     @Qualified("passwordEncoder")
     @Autowired
     PasswordEncoder bCryptPasswordEncoder;