问题描述
我正在尝试使用在数据库中散列的密码来验证我的用户给定的密码,但我想我正在比较两个给定的密码?有没有更好(或适当)的方法来做到这一点?
我也不确定应该使用什么异常来解决密码不匹配的问题。
控制器代码-
@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 的实例,而不是抛出异常。而不是:
return new UsernameNotFoundException("Credentials don't match");
改为:
throw new UsernameNotFoundException("Credentials don't match");