密码验证方法成功,失败
Password authentication method is giving success, on failure
我正在尝试使用数据库中散列的密码来验证我的用户给定密码,但我想我正在比较给定的两者?有没有更好(或正确)的方法来做到这一点?
我也不确定我应该为密码不匹配使用什么异常。
控制器代码-
@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 为假,则您将返回 UsernameNotFoundException 的实例,而不是抛出异常。而不是:
return new UsernameNotFoundException("Credentials don't match");
改为:
throw new UsernameNotFoundException("Credentials don't match");
我正在尝试使用数据库中散列的密码来验证我的用户给定密码,但我想我正在比较给定的两者?有没有更好(或正确)的方法来做到这一点?
我也不确定我应该为密码不匹配使用什么异常。
控制器代码-
@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 为假,则您将返回 UsernameNotFoundException 的实例,而不是抛出异常。而不是:
return new UsernameNotFoundException("Credentials don't match");
改为:
throw new UsernameNotFoundException("Credentials don't match");