【问题标题】:How to store and read passwords using Bcrypt如何使用 Bcrypt 存储和读取密码
【发布时间】:2016-12-18 13:37:44
【问题描述】:

我在使用 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());

然后我尝试使用休眠模式从数据库中读取数据

FROM Login WHERE email = :email AND password = :password AND email_confirmed = 1"

【问题讨论】:

    标签: spring passwords bcrypt


    【解决方案1】:

    为确保在用户输入其凭据时密码匹配,无需再次对密码进行编码以验证您从数据库获得的编码密码。

    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);
        }
    

    【讨论】:

    • 谢谢!这解决了我的问题。有时我只是瞎了
    猜你喜欢
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-07
    • 1970-01-01
    • 2017-10-13
    • 1970-01-01
    相关资源
    最近更新 更多