knowing better authentication with Passport / JwtStrategy

送分小仙女□ 提交于 2020-01-06 07:18:16

问题


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:


  1. That's fine. Both cases will result in undefined being returned anyways.
  2. Middleware is executed in the order in which they are defined. So requireAuth will always execute first and then function(req, res){}. But if requireAuth fails 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!