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

前端 未结 3 1307
遇见更好的自我
遇见更好的自我 2020-12-15 10:04

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

3条回答
  •  再見小時候
    2020-12-15 11:00

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

提交回复
热议问题