简体   繁体   English

Express中间件Passport没有未经授权的响应

[英]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 例2
This works but when the JWT is not set, I get res = null when I think I should be getting an 401 response. 这有效,但是当没有设置JWT时,我认为我应该得到401响应时res = null

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 例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. 如果没有设置JWT,那么我得到正确的401响应,但如果设置了,我就无法返回user因为res不存在。

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? 那么如何将res传递给这个函数呢?

Example 1 例1

In your first example, it looks like you've just mixed up the order of req and res in your function call. 在您的第一个示例中,您似乎只是在函数调用中混合了reqres的顺序。 It should be 它应该是

})(req, res, next);

not

})(res, req, next);

Example 2 例2

In your second example, I think you're using the callback to passport.authenticate incorrectly. 在您的第二个示例中,我认为您正在使用passport.authenticate回调错误。

The passport.authenticate method is just middleware to be called before your actual route gets hit. passport.authenticate方法只是在实际路由被命中之前调用的中间件。 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. 如果用户未经过身份验证, authenticate方法应该使用适当的状态代码来处理响应,因此您可以安全地在路由回调中调用req.user并知道用户已通过身份验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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