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

Bcryptjs compare验证失败:读取数据库用户密码时不生效

密码验证失败问题:bcrypt验证返回false的排查

可正常运行的测试代码

// 密码验证测试
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash("testing", salt);

const plaintextPassword = "testing"; // 用户登录时输入的明文密码
const storedHash = hashedPassword; // 数据库中存储的哈希值

const isValidPassword2 = await bcrypt.compare(
  plaintextPassword,
  storedHash
);
console.log("测试密码: " + plaintextPassword);
console.log("测试存储的哈希: " + storedHash);
console.log(isValidPassword2); // 密码正确时应返回true

// 测试结束

输出结果:

测试密码: testing
测试存储的哈希: $2a$10$k9h8yGCntskaRbPU6cMuPuzovwdn3AUE9JrOx1k74ZYImSAMUnyLa
true

我的代码无法正常验证

register/route.js(注册逻辑)

// 哈希密码
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);

// 创建新用户
const newUser = new User({
  username,
  email,
  password: hashedPassword,
});

login/route.js(登录验证逻辑)

const isValidPassword = await bcrypt.compare(password, user.password);
console.log("输入的密码: " + password);
console.log("数据库存储的密码哈希: " + user.password);
console.log(isValidPassword);

输出结果:(注:test4确实是该用户的正确密码)

输入的密码: test4
数据库存储的密码哈希: $2a$10$RtI4wnOtcuJL3N6xpGdFgOrU2ij9aUU4tzTyOwEEX4XpOEmf03iUO
false

User.js(Mongoose用户模型)

import mongoose from "mongoose";
import bcrypt from "bcryptjs";

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) {
  if (!this.isModified("password")) {
    return next();
  }

  const salt = await bcrypt.genSalt(10);
  this.password = await bcrypt.hash(this.password, salt);
  next();
});

// 避免重复定义模型
const User = mongoose.models.Users || mongoose.model("Users", userSchema);

export default User;

疑问

不确定问题出在哪里,是不是用户Schema里的pre-save钩子对密码做了二次哈希?但有人告诉我应该用这种方式存储密码,求帮忙排查原因!

内容的提问来源于stack exchange,提问作者Nerfed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 02:25:24