【问题标题】:Password authentication method is giving success, on failure密码验证方法成功,失败
【发布时间】:2021-06-17 07:13:18
【问题描述】:

我正在尝试使用数据库中散列的密码验证我的用户给定密码,但我想我正在比较两者?有没有更好(或正确)的方法来做到这一点?

我也不确定密码不匹配应该使用什么异常。

控制器代码 -

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

【问题讨论】:

  • hashedPassword 始终为空字符串。您是否将密码存储在数据库中,其值为空字符串?
  • @Boug 不,我没有。请原谅我的无知,我是 BCrypt 的新手,对匹配感到困惑。
  • 您是遇到异常还是某些特定的东西不起作用?可以将问题改写得更具体,否则这可能是题外话 - 请参阅stackoverflow.com/help/on-topic
  • @KevinHooke 它允许我在密码不匹配时登录
  • Boug 指出,当您调用 bcryptEncoder.matches(password, hashedPassword); hashedPassword 的值始终为“”(您在上一行中设置了它)。除非您的用户密码也是“”,否则这将永远无法使用?

标签: java authentication passwords bcrypt


【解决方案1】:

如果 isPasswordMatched 为 false,您将返回一个 UsernameNotFoundException 实例,而不是引发异常。而不是:

return new UsernameNotFoundException("Credentials don't match");

改成:

throw new UsernameNotFoundException("Credentials don't match");

【讨论】:

  • 这绝对可以防止它接受虚假密码。现在我需要弄清楚如何将它与实际的数据库密码进行比较。看来我没有正确调用它...
  • 您需要将 existingUser.getPassword() (这是您从数据库中检索到的内容吗?)与用户输入的编码密码进行比较,我认为是您的 user.getPassword()跨度>
猜你喜欢
  • 2017-12-22
  • 2020-09-21
  • 2015-04-19
  • 2017-04-03
  • 2016-05-27
  • 2017-11-09
  • 1970-01-01
  • 2022-08-15
  • 1970-01-01
相关资源
最近更新 更多