问题
On one working project I downloaded from internet...
In one location of the code I have the following:
passport.use(new JwtStrategy({
secretOrKey: credentials.secret,
jwtFromRequest: ExtractJwt.fromAuthHeader(),
},
function(payload, done) {
User.findById(
payload._id,
function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
return done(null, user);
} else {
return done(null, false);
}
}
);
}
));
In other location of the code I have the following:
var requireAuth = passport.authenticate('jwt', { session: false });
//...
module.exports = function(app) {
//...
authRoutes.get('/protected', requireAuth, function(req, res) {
res.send({ content: 'Success' });
});
//...
}
I have 2 questions here:
1- What about if instead doing: return done(err, false); we do: done(err, false); without return?
2- Is the 3rd argument (that middleware function) in the call of: authRoutes.get(*, *, *) always reached no matter what's going on inside the function: function(payload, done){} (second argument on: new JwtStrategy(*, *)? Notice that middleware function (that 3rd argument) returns a Success response. What about if something goes wrong inside the JWT authentication process?
回答1:
- That's fine. Both cases will result in
undefinedbeing returned anyways. - Middleware is executed in the order in which they are defined. So
requireAuthwill always execute first and thenfunction(req, res){}. But ifrequireAuthfails for whatever reason,function(req, res){}will be skipped in the middleware stack. Any errors should be handled in error middleware. If you do not handle them, then the whole application will crash.
来源:https://stackoverflow.com/questions/50048669/knowing-better-authentication-with-passport-jwtstrategy