barro32
barro32

Reputation: 2708

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?

Upvotes: 3

Views: 635

Answers (1)

Sean
Sean

Reputation: 372

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.

Upvotes: 1

Related Questions