如何在保存到db之前哈希密码以与护照模块(护照本地)兼容 [英] How to hash password before saving to db to be compatible with passport module (passport local)
问题描述
我使用护照本地护照策略进行身份验证。在我的快递服务器中,我收到了一个注册帖子请求,我应该为新用户保存密码到db。但是我需要在保存到db之前散列密码。
I am using passport-local strategy of passport for authentication. In my express server, I am getting a register post request and I should save password to db for a new user. But I need to hash the password before saving to db.
但我不知道如何散列它,因为护照将通过散列登录密码凭证来验证用户,以匹配来自db的哈希密码。我应该如何哈希我的密码?
But I am not sure how to hash it, since passport will authenticate user by hashing the login password credential to match my hashed password from db. How should I hash my passwords ?
我正在使用模块。
推荐答案
passport-local
不会哈希你的密码 - 它将凭据传递给您的验证回叫用于验证,您负责处理凭据。因此,您可以使用任何哈希算法,但我相信 bcrypt 是最受欢迎的。
passport-local
does not hash your passwords - it 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 is the most popular.
您在注册处理程序中哈希密码:
You hash the password in your register handler:
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
});
});
});
然后在验证回调中,您将提供的密码与哈希值进行比较:
Then in your verify callback you compare the provided password to the hash:
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);
}
});
}));
这篇关于如何在保存到db之前哈希密码以与护照模块(护照本地)兼容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!