简体   繁体   中英

Express middleware Passport not responding unauthorized

Passport

passport.use('jwt', new JwtStrategy(opts, function(jwt_payload, done) {
    User.where({id: jwt_payload.id}).fetch().then(function(user) {
        if(user) {
            return done(null, user);
        } else {
            return done(null, false);
        }
    }).catch(function(err) {
        return done(err, false);
    });
}));

Example 2
This works but when the JWT is not set, I get res = null when I think I should be getting an 401 response.

app.get('/user', getProfile);
getProfile = function(req, res, next) {
    passport.authenticate('jwt', {session: false}, function(err, user, info) {
        if(user) {
            res.json(user);
        } else {
            res.json(err);
        }
    })(res, req, next);
};

Example 2
When the JWT is not set then I get the correct 401 response but if it is set I can't get user returned because res doesn't exist.

app.get('/user', passport.authenticate('jwt', {session: false}, getProfile);
getProfile = function(err, user) {
    if(user) {
        res.json(user); 
    } else {
            res.json(err);
    }
};

So how do I pass res into this function?

Example 1

In your first example, it looks like you've just mixed up the order of req and res in your function call. It should be

})(req, res, next);

not

})(res, req, next);

Example 2

In your second example, I think you're using the callback to passport.authenticate incorrectly.

The passport.authenticate method is just middleware to be called before your actual route gets hit. Its callback does not replace the regular route callback function you would define to handle sending a response - you still need to provide a route callback after the middleware.

app.get('/user',
passport.authenticate('jwt', { session: false }),
function(req, res, next) {
  res.json(req.user);
});

The authenticate method should handle responding with an appropriate status code if the user was not authenticated, so you can safely call req.user in your route callback and know the user is authenticated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM