我正在进行本地登录,并且知道我的密码以纯文本格式存储在h2数据库中。

我想在 Spring 使用Bcrypt,但是在应用程序启动时出现此错误:

Field bCryptPasswordEncoder in com.alert.interservices.uaa.Bootstrap required a bean of type 'org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder' that could not be found.

要使用Bcrypt,我只能将其自动连接到 Controller 中并加密密码。
填充数据库时,我在Bootstrap上执行了相同的操作:

Controller :
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;

/**
 *
 * @param user the user that is trying to access
 * @return the user if it is successfull or a bad request if not
 */
@RequestMapping(value = "/authenticate", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Object authenticate(@RequestBody UserEntity user) {

    logger.debug("Begin request UAAController.authenticate()");

    String encriptedPasswd=bCryptPasswordEncoder.encode(user.getPassword().getPassword());

    UserEntity usr = authenticationService.authenticate(user.getName(), encriptedPasswd);

    (...)

bootstrap :
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;

@GetMapping("/test")
public void fillDatabse() {


    String encodedPw=bCryptPasswordEncoder.encode("test");
    Password p = new Password(encodedPw);

我在做什么错?

最佳答案

BCryptPasswordEncoder不是bean,不能 Autowiring 。

用:

Password p = new Password(new BCryptPasswordEncoder().encode(encodedPw));

代替
String encodedPw=bCryptPasswordEncoder.encode("test");
Password p = new Password(encodedPw);

并删除
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;

同时在您的 Controller 中进行这些更改

10-07 16:33