使用BCrypt时遇到问题。 我想以安全的方式存储用户密码,因此,我使用Spring的BCrypt存储加密的密码。 我现在面临的问题是BCrypt生成随机盐,当然,密码无法解密。 但是我怎样才能处理登录呢?
private PasswordEncoder encoder = new BCryptPasswordEncoder();
public String encryptPassword(String password) {
String encryptedValue = encoder.encode(password);
Assert.isTrue(encoder.matches(password, encryptedValue));
return encryptedValue;
}
在用户输入凭据时,我需要做些什么才能确保密码匹配?
String encryptedPassword = encryptionGenerator.encryptPassword(loginCredentials.getPassword());
然后我尝试用数据库读取hibernate
FROM Login WHERE email = :email AND password = :password AND email_confirmed = 1"
答案 0 :(得分:2)
要确保在用户输入凭据时密码匹配,则无需再次对密码进行编码以验证从数据库获取的编码密码。
BCryptPasswordEncoder 类仅匹配密码字符串值。
我尝试了以下方式并为我工作。如果您关注的是验证用户,请尝试以下方式:
@Autowired
UserRepository userRepository;
public void validateUser(User user) {
// get User entity from database using your user repository
final User currentUser = userRepository.findByEmailId(user.getUserName());
final BCryptPasswordEncoder pwEncoder = new BCryptPasswordEncoder();
if (pwEncoder.matches(user.getPassword(), currentUser.getPassword())) {
// user password is correct
}
else{
//user password incorrect
}
}
public interface UserRepository extends JpaRepository<User, Long>{
@Query("FROM Login WHERE emailId = :emailId")
User findByEmailId(@param("emailId") String emailId);
}
@Autowired
UserRepository userRepository;
public void validateUser(User user) {
// get User entity from database using your user repository
final User currentUser = userRepository.findByEmailId(user.getUserName());
final BCryptPasswordEncoder pwEncoder = new BCryptPasswordEncoder();
if (pwEncoder.matches(user.getPassword(), currentUser.getPassword())) {
// user password is correct
}
else{
//user password incorrect
}
}
public interface UserRepository extends JpaRepository<User, Long>{
@Query("FROM Login WHERE emailId = :emailId")
User findByEmailId(@param("emailId") String emailId);
}