Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

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

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.

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 ?

I am using this module.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...