首页 > 解决方案 > 在 Spring 中使用 Bcrypt

问题描述

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

我想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我只在我的控制器中自动连接它并加密密码。填充数据库时,我在 Bootstrap 上做了同样的事情:

控制器:

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

    (...)

引导程序:

@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;

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


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

我做错了什么?

标签: javaspringspring-bootbcrypt

解决方案


BCryptPasswordEncoder不是 bean,你不能自动装配它。

利用:

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

代替

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

并删除

@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;

还要在您的控制器中进行这些更改


推荐阅读