Java 密码身份验证方法在失败时提供成功
我试图用数据库中散列的密码验证我的用户给定密码,但我想我是在比较这两个给定密码?有没有更好的(或适当的)方法 我也不确定密码不匹配时应该使用什么异常 控制器代码-Java 密码身份验证方法在失败时提供成功,java,authentication,passwords,bcrypt,Java,Authentication,Passwords,Bcrypt,我试图用数据库中散列的密码验证我的用户给定密码,但我想我是在比较这两个给定密码?有没有更好的(或适当的)方法 我也不确定密码不匹配时应该使用什么异常 控制器代码- @PostMapping(path = "/login") public Object login(User user) throws UsernameNotFoundException { User existingUser = userService.findUserByEmail(user.getEm
@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;
}
}
如果isPasswordMatched为false,则返回UsernameNotFoundException的实例,而不是引发异常。而不是:
返回新用户名NotFoundException(“凭据不匹配”)代码>
将其更改为:
抛出新用户名NotFoundException(“凭据不匹配”)代码>哈希密码始终为空字符串。您是否在DB中存储了一个值为空字符串的密码?@Boug否我没有。请原谅我的无知,我是BCrypt的新手,对匹配感到困惑。您是否遇到了例外情况,或者某些特定的东西不起作用?可以将问题改写为更具体的问题,否则这可能会偏离主题-请参阅@KevinHooke它允许我在密码不匹配时登录Bug指出,当您调用bcryptEncoder.matches(password,hashedPassword)时;hashedPassword的值始终为“”(您在前一行中设置了它)。除非您的用户密码也是“”,否则这将永远不会起作用。这绝对可以防止它接受错误的密码。现在我需要弄清楚如何将它与实际的DB密码进行比较。似乎我没有正确调用它…您需要将existingUser.getPassword()(这是您从数据库检索到的吗?)与用户输入的编码密码进行比较,我认为这是您的用户。getPassword()