【发布时间】:2021-06-17 07:13:18
【问题描述】:
我正在尝试使用数据库中散列的密码验证我的用户给定密码,但我想我正在比较两者?有没有更好(或正确)的方法来做到这一点?
我也不确定密码不匹配应该使用什么异常。
控制器代码 -
@PostMapping(path = "/login")
public Object login(User user) throws UsernameNotFoundException {
User existingUser = userService.findUserByEmail(user.getEmail());
if (existingUser.getEmail() == null || existingUser.getEmail().equals("")) {
return new UsernameNotFoundException("User not found");
}
String password = user.getPassword();
BCryptPasswordEncoder bcryptEncoder = new BCryptPasswordEncoder();
String hashedPassword = "";
boolean isPasswordMatched = bcryptEncoder.matches(password, hashedPassword);
if (!isPasswordMatched) {
return new UsernameNotFoundException("Credentials don't match");
} else {
return existingUser;
}
}
【问题讨论】:
-
hashedPassword 始终为空字符串。您是否将密码存储在数据库中,其值为空字符串?
-
@Boug 不,我没有。请原谅我的无知,我是 BCrypt 的新手,对匹配感到困惑。
-
您是遇到异常还是某些特定的东西不起作用?可以将问题改写得更具体,否则这可能是题外话 - 请参阅stackoverflow.com/help/on-topic
-
@KevinHooke 它允许我在密码不匹配时登录
-
Boug 指出,当您调用 bcryptEncoder.matches(password, hashedPassword); hashedPassword 的值始终为“”(您在上一行中设置了它)。除非您的用户密码也是“”,否则这将永远无法使用?
标签: java authentication passwords bcrypt