首页 > 解决方案 > 使用 express-jwt,我可以返回 401 以外的其他状态码吗?

问题描述

我正在使用 express-jwt。我想在失败时发回不同的状态码。我实际上设置了 2 个不同的 express-jwt 中间件,一个需要凭据,另一个可以选择解码令牌(如果存在)。对于后者,如果令牌存在但过期,我想返回不同的状态代码,因为在 401 上,我的应用程序会自动将用户重定向到登录页面,我不希望这种情况发生在可选的身份验证中。

这是我的 express-jwt 设置:

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

exports.decodeAuthIfExist = jwt({
  secret: jwksRsa.expressJwtSecret({
    cache: true,
    rateLimit: true,
    jwksRequestsPerMinute: 5,
    jwksUri: `https://${process.env.AUTH0_DOMAIN}/.well-known/jwks.json`
  }),
  credentialsRequired: false,
  audience: process.env.AUTH0_AUDIENCE,
  issuer: `https://${process.env.AUTH0_DOMAIN}/`,
  algorithms: ['RS256']
});

这就是我使用它的方式:

app.get('/resource',
    auth.decodeAuthIfExist,
    resource.get);

例如,我需要修改什么以返回状态码 402。

标签: node.jsexpressjwtexpress-jwt

解决方案


express-jwt will throw an UnauthorizedError error. It does not set the status at all.

You have error middleware defined somewhere that is handling the exception.


推荐阅读