首页 > 解决方案 > 在 Hapi-auth-jwt2 中,令牌过期时出现错误 500 而不是 401

问题描述

我正在使用 Hapi-auth-jwt2 并在我的 JWT 过期后遇到问题,而不是收到 401 错误我收到 500 服务器错误,

这是我的代码:

const prepare = async () => {
if(prepared){
    return;
}
await server.register(documentor as any);
server.auth.strategy('token','jwt',{
    key:JWT_TOKEN,
    validate: AuthService.verify,
    verifyOptions:{
        algorithms:['HS256']
    }
});
server.auth.default('token');
server.validator(Joi);
server.route(routes);
prepared = true;}

如果令牌有效,它工作正常,但如果令牌无效,它假设返回 401,但我得到 500,如果我在其中使用ignoreExpiration: trueverifyOptions再次工作。

这与#328有关,因为我使用的是 v10.2.0,所以它应该已修复,但在我的情况下仍然无法正常工作。

此外,如果令牌无效或过期令牌validate: AuthService.verify未被调用。

我不知道它有什么问题。请帮忙。

如果有帮助,这是一条调试错误消息

Debug: auth, unauthenticated, error, token 
Error: Expired token
at Object.raiseError (/Users/tinkeshwar/Sites/proj/tool/node_modules/hapi-auth-jwt2/lib/index.js:302:45)
at Object.internals.authenticate (/Users/tinkeshwar/Sites/proj/tool/node_modules/hapi-auth-jwt2/lib/index.js:171:26)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at Object.authenticate (/Users/tinkeshwar/Sites/proj/tool/node_modules/hapi-auth-jwt2/lib/index.js:353:22)
at exports.Manager.execute (/Users/tinkeshwar/Sites/proj/tool/node_modules/@hapi/hapi/lib/toolkit.js:60:28)
at module.exports.internals.Auth._authenticate (/Users/tinkeshwar/Sites/proj/tool/node_modules/@hapi/hapi/lib/auth.js:258:30)
at Request._lifecycle (/Users/tinkeshwar/Sites/proj/tool/node_modules/@hapi/hapi/lib/request.js:372:32)
at Request._execute (/Users/tinkeshwar/Sites/proj/tool/node_modules/@hapi/hapi/lib/request.js:280:9)

调试:内部,错误 ValidationError:不允许使用“属性”

标签: node.jshapijs

解决方案


 statusCode: Joi.any().optional().example(401),
 error: Joi.any().example("Unauthorized"),
 message: Joi.any().example("Missing authentication"),
 attributes: {error: "Expired token"}
}).label("Unauthorized Error");

您可能应该比较您的架构以获取未经授权的响应。


推荐阅读