尝试使用bcryptjs比较密码时有太多时间,所以我可以签署JWT但尝试登录我无法比较签署令牌并发送给客户端。
问题
我可以哈希密码并存储到数据库中,我遇到问题的方法是使用.compare()
方法并传入hash
参数。我不太确定要传递什么作为hash
值。
技术:
user.routes.js
var express = require('express');
var router = express.Router();
var jwt = require('jsonwebtoken');
var bcrypt = require('bcryptjs');
var salt = bcrypt.genSaltSync(10);
var config = require('../config/database');
User = require('../models/user.model.js');
// Create new User
router.post('/', function(req, res){
var user = req.body;
if(!req.body.email || !req.body.password){
res.json({success: false, message: 'Please pass email and password'});
} else {
User.addUser(user, function(err, user){
if(err){
res.send(err);
}
bcrypt.genSalt(10, function(err, salt){
bcrypt.hash(user.password, salt, function(err,hash){
user.password = hash;
user.save();
console.log('new user', user);
res.json({success: true, message: 'Create user successful'});
})
})
});
}
});
在密码比较期间收到错误:
// Authenticate a User
//email: test@test.com
//password: password
router.post('/login', function(req, res){
User.findOne({ email: req.body.email }, function (err, user){
if (err){
res.send(err);
}
if(!user){
res.json({ success: false, message: 'Authentication failed. User not found'});
} else if (user) {
// where does this hash value get defined and passed in?
bcrypt.compare(req.body.password, hash, function(err, res){
if(user.password != req.body.password){
console.log('password incorrect');
//res.json({ success: false, message: 'Authentication failed. Password incorrect'});
} else {
var token = jwt.sign({
email: user.email
}, config.secret, {
expiresIn: 60 // expressed in seconds
});
console.log('token contents', token);
res.json({
success: true,
message: 'Enjoy your token!',
token: token
});
}
});
}
});
});
答案 0 :(得分:2)
您必须传递给compare方法的哈希值是您调用bcrypt.hash
方法时获得的哈希值。我想你在某些数据库中保存了与用户关联的哈希值,因此你必须得到该哈希并将其作为第二个参数传递给compare方法。
我认为你在比较方法的回调中做错了比较。你不应该比较密码,比较方法为你做。您只需检查res
是真还是假。如果是,那么密码是相同的,其他情况则不同。
如果您对本文中的实现有更多疑问,那么您有一个非常简单的示例: https://solidgeargroup.com/password-nodejs-mongodb-bcrypt?lang=es
它是用承诺书写的,但它很容易理解。