【发布时间】:2021-11-15 15:23:47
【问题描述】:
bcrypt.compare 在将来自数据库的结果与字符串密码进行比较时,总是返回 false。
您好,亲爱的,我正在尝试为我的表单创建登录身份验证。我使用哈希密码创建用户,然后尝试登录,但在比较纯文本密码和哈希密码 bcrypt.compare 返回 false。
当我创建一个哈希密码并在同一个函数中进行比较时,它运行良好,但如果我再次从数据库中获取哈希密码,它会返回 false。
const myFunction = async ()=>{
const passwordText = 'abcd123'
const hashedPassword = await bcrypt.hash(passwordText, 10)
console.log(passwordText)
console.log(hashedPassword)
const isMatch = await bcrypt.compare(passwordText, hashedPassword)
console.log(isMatch)
}
myFunction()
输出
abcd123
$2b$10$yNuWJBqlV8NjHrmqOfwaSuKDk.rSB9O6KstAmUpS2770GC1Nlyjw.
true
但是当我使用这样的哈希密码创建用户时
router.post('/user/signup', async (req, res)=>{
try{
const user = new User(req.body)
const salt = await bcrypt.genSalt(10)
user.password = await bcrypt.hash(user.password, salt)
await user.save().then((user)=>{
res.status(201).send(user)
}).catch((e)=>{
res.send(e)
})
} catch(e){
res.status(500).send()
}
})
当我在登录路径中比较它时,它返回 false
router.post("/user/login", async (req, res) => {
const body = req.body;
const user = await User.findOne({ email: body.email });
if (user) {
// check user password with hashed password stored in the database
const validPassword = await bcrypt.compare(body.password, user.password);
if (validPassword) {
res.status(200).json({ message: "Valid password" });
} else {
res.status(400).json({ error: "Invalid Password" });
}
} else {
res.status(401).json({ error: "User does not exist" });
}
});
我尝试在这样的用户架构中创建哈希密码
userSchema.pre('save', async function(next){
const user = this
if(user.isModified('password')){
user.password = await bcrypt.hash(user.password, 10)
}
console.log('Befor saveing')
next()
})
再次返回 false。
如果有任何帮助,我将不胜感激,谢谢。
更新和解决方案
最后,this post 解决了我的问题,一切正常。
当我在密码字段中创建用户时,我使用了lowercase: true,,然后,我删除了这个,现在 bcrypt 比较正在工作,我得到了True 返回。
【问题讨论】:
标签: node.js mongodb authentication bcrypt password-hash