繁体   English   中英

Bcryptjs无法比较密码Nodejs

[英]Bcryptjs unable to compare passwords Nodejs

有一段时间试图使用bcryptjs比较密码,所以我可以签署一个JWT但尝试登录我无法比较签署令牌并发送给客户端。

问题

我可以散列密码并存储到数据库中,我遇到的问题是使用.compare()方法并传入hash参数。 我不太确定要传入什么作为hash值。

技术:

  • NodeJS:5.4.1
  • bcryptjs:2.3.0
  • 表达:4.14.0
  • body-parser:1.15.2
  • MongoDB:3.2.5
  • 猫鼬:4.6.1

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
          });
        }
      });
    }
  });
});

您必须传递给compare方法的哈希值是您在调用bcrypt.hash方法时获得的哈希值。 我想你在某些数据库中保存了与用户关联的哈希值,因此你必须得到该哈希并将其作为第二个参数传递给compare方法。

我认为你在比较方法的回调中做错了比较。 你不应该比较密码,比较方法为你做。 你只需检查res是真还是假。 如果是,那么密码是相同的,其他情况则不同。

如果您对本文中的实现有更多疑问,您可以使用一个非常简单的示例: https//solidgeargroup.com/password-nodejs-mongodb-bcrypt?lang = es

它是用承诺书写的,但它很容易理解。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM