使用 PassportJS,如何向本地身份验证策略传递额外的表单字段?

我正在使用 passportJS,我想提供的不仅仅是 req.body.usernamereq.body.password,我的认证策略(护照-本地)。

我有3个表单字段: usernamepasswordfoo

我如何从我的本地策略访问 req.body.foo,它看起来像:

passport.use(new LocalStrategy(
{usernameField: 'email'},
function(email, password, done) {
User.findOne({ email: email }, function(err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Unknown user' });
}
if (password != 1212) {
return done(null, false, { message: 'Invalid password' });
}
console.log('I just wanna see foo! ' + req.body.foo); // this fails!
return done(null, user, aToken);


});
}
));

我在我的路由(不作为路由中间件)中这样称呼它:

  app.post('/api/auth', function(req, res, next) {
passport.authenticate('local', {session:false}, function(err, user, token_record) {
if (err) { return next(err) }
res.json({access_token:token_record.access_token});
})(req, res, next);


});
44023 次浏览

There's a passReqToCallback option that you can enable, like so:

passport.use(new LocalStrategy(
{usernameField: 'email', passReqToCallback: true},
function(req, email, password, done) {
// now you can check req.body.foo
}
));

When, set req becomes the first argument to the verify callback, and you can inspect it as you wish.

In most common cases we need to provide 2 options for login

  • with email
  • with mobile

Its simple , we can take common filed username and query $or by two options , i posted following snippets,if some one have have same question .

We can also use 'passReqToCallback' is best option too , thanks @Jared Hanson

passport.use(new LocalStrategy({
usernameField: 'username', passReqToCallback: true
}, async (req, username, password, done) => {
try {
//find user with email or mobile
const user = await Users.findOne({ $or: [{ email: username }, { mobile: username }] });


//if not handle it
if (!user) {
return done(null, {
status: false,
message: "That e-mail address or mobile doesn't have an associated user account. Are you sure you've registered?"
});
}


//match password
const isMatch = await user.isValidPassword(password);
debugger
if (!isMatch) {
return done(null, {
status: false,
message: "Invalid username and password."
})
}


//otherwise return user
done(null, {
status: true,
data: user
});
} catch (error) {
done(error, {
status: false,
message: error
});
}
}));