Bcrypt哈希匹配失败求助:输入密码与哈希密码不匹配排查
密码哈希匹配失败问题排查与解决
问题场景
使用Postman测试登录功能时,MongoDB中已存在注册用户,但登录时始终返回密码不匹配的错误,经排查确认问题出在密码哈希环节。
相关代码
User.js(用户模型文件)
UserSchema.pre("save",function(next) { if (!this.isModified("password")) { next(); } bcrypt.genSalt(10, (err, salt) => { if (err) next(err); bcrypt.hash("this.password", salt, (err, hash) => { if (err) next(err); this.password = hash; next(); }); }); })
inputHelper.js
const bcrypt = require("bcryptjs") const validateUserInput = (email, password) => { return email && password; } const comparePassword = (password, hashedPassword) => { return bcrypt.compareSync(password, hashedPassword); } module.exports = { comparePassword, validateUserInput };
Auth.js
const { validateUserInput, comparePassword } = require("../helpers/input/inputHelper"); const login = asyncErrorWrapper(async (req, res, next) => { const {email, password} = req.body; if (!validateUserInput(email, password)) { return next(new CustomError("Please check your inputs", 400)); } const user = await User.findOne({email}).select("+password"); if (comparePassword(password, user.password)) { sendJwtToClient(user,res,200); // Success }else{ return next(new CustomError("Please check your credentials", 400)); // Fail } });
问题根源
在User.js的pre-save钩子函数中,调用bcrypt.hash时错误地将this.password用双引号包裹,导致实际哈希的是字符串字面量"this.password",而非用户输入的真实密码值。这就导致数据库中存储的哈希值和登录时传入的密码永远无法匹配。
解决方法
修改User.js中的哈希代码,去掉this.password的双引号:
bcrypt.hash(this.password, salt, (err, hash) => { if (err) next(err); this.password = hash; next(); });
内容的提问来源于stack exchange,提问作者Ciyradyl
相关产品推荐
相关产品推荐

