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功能永远不会触摸。

我不知道什么是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)

最新更新