0

我有这个中间件功能,它检查用户是否登录,因为我也有 web 应用程序和 android 平台,因此我使用 android 和 web 的令牌,我使用 session,默认情况下是通过护照管理器.

In my function我正在检查如果我有一个 Authorization 标头,我知道它是我的 android 平台,因此通过验证 jwt 令牌来验证用户,但它总是向我发送 401 未经授权而不设置 req.user。

这是中间件功能,如果有人可以指出我的错误,我的逻辑出错了。

var jwt_auth = require('express-jwt')

// route middleware to make sure a user is logged in
function isLoggedIn(req, res, next) {

    if (req.get("Authorization")) {
        jwt_auth({secret: 'somesecret'});
        if (req.user) {
            return next();
        }
        res.send(200, "Unauthorized access");
    }
    else {
        // if user is authenticated in the session, carry on
        if (req.isAuthenticated())
            return next();

        // if they aren't redirect them to the home page
        res.redirect('/');
    }
}
4

1 回答 1

2

这是因为 jwt_auth 是一个异步操作,而您的 res.send(200, "Unauthorized access") 永远不会等待 jwt_auth 完成。

你应该看看 express-jwt 的例子。

最基本的是

var jwt = require('express-jwt');

app.get('/protected',
    jwt({secret: 'shhhhhhared-secret'}),
    function(req, res) {
        if (!req.user.admin) return   res.sendStatus(401);
       res.sendStatus(200);
});

如果要传递自定义函数从请求中提取令牌,请使用 getToken 选项,以下示例取自 express jwt 的 README,您可以根据需要修改该函数。

app.use(jwt({
  secret: 'hello world !',
  credentialsRequired: false,
  getToken: function fromHeaderOrQuerystring (req) {
  if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
        return req.headers.authorization.split(' ')[1];
  } else if (req.query && req.query.token) {
      return req.query.token;
  }
    return null;
  }
}));
于 2017-03-31T11:27:55.740 回答