如何在保存到db之前哈希密码以与护照模块(护照本地)兼容

问题描述 投票:7回答:3

我使用护照本地护照策略进行身份验证。在我的快递服务器中,我收到了一个注册帖子请求,我应该为新用户保存密码到db。但是我需要在保存到db之前散列密码。

但我不知道如何散列它,因为护照将通过散列登录密码凭证来验证用户,以匹配来自db的哈希密码。我应该如何哈希我的密码?

我正在使用这个module

javascript node.js passport.js
3个回答
16
投票

qazxsw poi不会哈希你的密码 - 它是qazxsw poi进行验证,你负责处理凭证。因此,您可以使用任何哈希算法,但我相信passport-local是最受欢迎的。

您在注册处理程序中哈希密码:

passes the credentials to your verify callback

然后在验证回调中,将提供的密码与哈希进行比较:

bcrypt

2
投票

你试过这个吗?

app.post('/register', function(req, res, next) { // Whatever verifications and checks you need to perform here bcrypt.genSalt(10, function(err, salt) { if (err) return next(err); bcrypt.hash(req.body.password, salt, function(err, hash) { if (err) return next(err); newUser.password = hash; // Or however suits your setup // Store the user to the database, then send the response }); }); });

passport.use(new LocalStrategy(function(username, password, cb) {
  // Locate user first here
  bcrypt.compare(password, user.password, function(err, res) {
    if (err) return cb(err);
    if (res === false) {
      return cb(null, false);
    } else {
      return cb(null, user);
    }
  });
}));

0
投票

当护照已经为我们提供时,我们为什么要选择哈希算法呢?我的意思是我们只需要将passport-local-mongoose插入我们的用户架构,例如:https://www.npmjs.com/package/passport-local-authenticate然后,在寄存器路径中我们告诉var auth = require('passport-local-authenticate'); auth.hash('password', function(err, hashed) { console.log(hashed.hash); // Hashed password console.log(hashed.salt); // Salt }); auth.hash('password', function(err, hashed) { auth.verify('password', hashed, function(err, verified) { console.log(verified); // True, passwords match )); }); auth.hash('password', function(err, hashed) { auth.verify('password2', hashed, function(err, verified) { console.log(verified); // False, passwords don't match )); }); 通过使用以下方式为我们进行散列:

UserSchema.plugin(passportLocalMongoose)

通过上面的操作,我们不需要处理散列,它将为我们完成。如果我错了或者你的问题错了,请纠正我。

© www.soinside.com 2019 - 2024. All rights reserved.