如何在保存到数据库之前散列密码以与护照模块(本地护照)兼容

How to hash password before saving to db to be compatible with passport module (passport local)

我正在使用 passport-local 策略进行身份验证。在我的快速服务器中,我收到一个注册 post 请求,我应该为新用户将密码保存到数据库。但是我需要在保存到数据库之前对密码进行哈希处理。

但我不确定如何对其进行哈希处理,因为护照将通过对登录密码凭据进行哈希处理以匹配我从 db 中得到的哈希密码来对用户进行身份验证。我应该如何散列我的密码?

我正在使用这个module

你试过吗?

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

passport-local 不会散列您的密码 - 它 passes the credentials to your verify callback for verification and you take care of handling the credentials. Thus, you can use any hash algorithm but I believe bcrypt 是最受欢迎的。

您在注册处理程序中散列密码:

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

当护照已经为我们提供时,我们为什么要使用哈希算法?我的意思是我们只需要将 passport-local-mongoose 插入到我们的用户模式中,例如:UserSchema.plugin(passportLocalMongoose) 然后,在注册路由中,我们只需告诉 passportLocalMongoose 使用以下命令为我们进行哈希处理:

User.register(new User({username:req.body.username}), req.body.password,function(err,newUser)
{ 
    if(err){
        something
    }else{
        something
    }
)

通过执行上述操作,我们不需要处理散列,它会为我们完成。如果我错了或者你的问题有误,请指正。