You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js+Bcrypt验证MongoDB存储的哈希密码失败问题求助

Node.js+Bcrypt验证MongoDB存储的哈希密码失败问题求助

大家好,我现在碰到了一个棘手的密码验证问题:注册用户时,密码的哈希值已经能正确存储到MongoDB里了,但登录环节用bcrypt.compare验证时始终返回false,导致登录失败,实在找不到问题所在,想请大家帮忙排查下。

先说明下我的技术环境:

  • 数据库:MongoDB
  • Node.js版本:v18.17.0
  • Bcrypt版本:5.1.1

以下是我的用户Schema代码:

const userSchema = new mongoose.Schema({
  username: { type: String, required: true, unique: true },
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },
});

userSchema.pre('save', async function (next) {
  try {
    if (!this.isModified('password')) {
      return next();
    }
    const hashedPassword = await bcrypt.hash(this.password, 10);
    this.password = hashedPassword;
    return next();
  } catch (error) {
    // 此处省略了错误处理代码
  }
})

还有AuthController.js里的登录逻辑片段:

loginUser: async (req, res) => {
  try {
    const { email, password } = req.body;
    const user = await User.findOne({ email });

    if (!user) {
      return res.status(401).json({ error: 'Invalid email or password.' });
    }

    const trimmedPassword = password.trim();
    console.log('Password received:', password);
    console.log('User password:', user.password);
    const passwordMatch = await bcrypt.compare(trimmedPassword, user.password);
    console.log(passwordMatch);

    if (!passwordMatch) {
      return res.status(401).json({ error: 'Invalid email or password.' });
    }

    // 生成JWT令牌
    const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, { expireIn: '1h' });
    res.json({ token, userId: user._id, username: user.username });
  } catch(error){
    // 此处省略了错误处理代码
  }
}

我用Postman测试登录时,返回的错误始终是Invalid email or password.,终端打印的日志如下:

Password received: abcd
User password: $2b$10$3XqxT29oUNX8Sr86i/woPufzHf6s7OjP4yyNdirtGk9Zj0T3MdkAC
false

已经确认注册时密码哈希是正确存储的,但登录时就是匹配不上,有没有大佬能帮我找找问题出在哪?

备注:内容来源于stack exchange,提问作者Dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.20 09:43:11