快速中间件超时问题

时间:2019-02-16 23:14:36

标签: node.js express

我有一个用于令牌验证的中间件。这是它的外观:

this.checkJwt =  jwt({
    secret: jwksRsa.expressJwtSecret({
        cache: true,
        rateLimit: true,
        jwksRequestsPerMinute: 5,
        jwksUri: process.env.AUTH0_JWKS,
    }),
    // Validate the audience and the issuer.
    audience: process.env.AUTH0_AUDIENCE,
    issuer: process.env.AUTH0_ISSUER,

    algorithms: ["RS256"],
});

然后我将其应用于路线:

app.route(routes.getUserInfo)
     .get(checkJwt, this.userController.me);

为什么当我用return语句重写中间件时,它停止工作?像这样:

this.checkJwt = (req, res, next) => {
    return jwt({
        secret: jwksRsa.expressJwtSecret({
            cache: true,
            rateLimit: true,
            jwksRequestsPerMinute: 5,
            jwksUri: process.env.AUTH0_JWKS,
        }),
        // Validate the audience and the issuer.
        audience: process.env.AUTH0_AUDIENCE,
        issuer: process.env.AUTH0_ISSUER,

        algorithms: ["RS256"],
    });
};

对于此中间件的每个请求,我都有超时异常。似乎next的功能永远不会触及。

1 个答案:

答案 0 :(得分:1)

我不知道什么是jwt方法-自定义中间件还是仅使用jwt包?

我还看到您正在返回jwt调用而未传递req, res, next

this.checkJwt = (req, res, next) => {
    return jwt({
        secret: jwksRsa.expressJwtSecret({
            cache: true,
            rateLimit: true,
            jwksRequestsPerMinute: 5,
            jwksUri: process.env.AUTH0_JWKS,
        }),
        // Validate the audience and the issuer.
        audience: process.env.AUTH0_AUDIENCE,
        issuer: process.env.AUTH0_ISSUER,

        algorithms: ["RS256"],
    });
};

调用中间件期间执行的结果是[Function](req, res, next),该结果应被执行-不返回。

因此,如果它是中间件,请尝试使用这样重写它:

const checkJwt = (req, res, next) => {
    jwt({
        secret: jwksRsa.expressJwtSecret({
            cache: true,
            rateLimit: true,
            jwksRequestsPerMinute: 5,
            jwksUri: process.env.AUTH0_JWKS,
        }),
        // Validate the audience and the issuer.
        audience: process.env.AUTH0_AUDIENCE,
        issuer: process.env.AUTH0_ISSUER,

        algorithms: ["RS256"],
    })(req, res, next);
};

app.get(routes.getUserInfo, checkJwt, this.userController.me)

但是,如果jwt方法不是中间件,并且返回true or false作为结果:

const checkJwt = (req, res, next) => {
    const result = jwt({
        secret: jwksRsa.expressJwtSecret({
            cache: true,
            rateLimit: true,
            jwksRequestsPerMinute: 5,
            jwksUri: process.env.AUTH0_JWKS,
        }),
        // Validate the audience and the issuer.
        audience: process.env.AUTH0_AUDIENCE,
        issuer: process.env.AUTH0_ISSUER,

        algorithms: ["RS256"],
    });

    // if jwt returns something (:
    if (!result) {
      return res.status(401).send('Unauthorized');
    }
    next();
};

app.get(routes.getUserInfo, checkJwt, this.userController.me)