Ошибка создания и внедрения BCryptPasswordEncoder в класс обслуживания - PullRequest
0 голосов
/ 30 марта 2020

Я хочу иметь sh и сохранить пароль в базе данных. Когда я пытаюсь внедрить bean-компонент PasswordEncoder в мой класс обслуживания, я получаю ошибку, указанную ниже.

Это мой первый проект, использующий модуль Spring-security, и буду признателен за ваш совет.

Spring Boot version:2.2.6.RELEASE

** SecurityConfiguration. java: класс конфигурации безопасности *

 @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: класс обслуживания для сохранения пользователя

 @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);
    }
    }

ОШИБКА

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

Пожалуйста, дайте мне знать если требуется дополнительный код и детали.

1 Ответ

1 голос
/ 30 марта 2020

Если вы не используете @Qualified("passwordEncoder") в классе обслуживания, тогда Spring будет искать bCryptPasswordEncoder в качестве компонента. В данный момент вы ищете бин с именем bCryptPasswordEncoder.

Измените его на

  @Autowired
  PasswordEncoder passwordEncoder;

или

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