【问题标题】:HapiJS scopes: Custom error message instead of "Insufficient scope"HapiJS 范围:自定义错误消息而不是“范围不足”
【发布时间】:2016-08-29 09:48:58
【问题描述】:

我将 HapiJS 用于我的 REST API。我还使用范围功能来实现对资源的简单的基于角色的访问。示例路由配置对象如下所示:

{
    method: 'GET',
    path: '/users/{userID}',
    config: {
        auth: {
            access: {
                scope: ['user-{params.userID}']
            }
        },
        handler: getUserHandler
    }
}

默认情况下,当当前经过身份验证的用户不需要 scope 来访问给定端点时(例如,scope: 'user-1' 尝试 GET /users/1 时),会返回错误响应:

{"statusCode":403,"error":"Forbidden","message":"Insufficient scope"}

我想要用自定义状态代码替换这个403 错误 和错误消息——我想返回404 Not Found。我想仅针对某些端点这样做。这可能吗?

【问题讨论】:

    标签: node.js hapijs


    【解决方案1】:

    您可以通过server.ext('onPostHandler', (request, reply) => {...进行操作

    您可以在请求中获取routeresponse 对象。

    response 对象包含isBoom,如果是真的,你应该得到response.output.statusCode,你可以验证它是否是403

    route 对象包含 path,您可以验证它是否是您想要的端点。

    类似这样的:

    server.ext('onPostHandler', (request, reply) => {
    
      const response = request.response;
    
      if (response.isBoom &&
         response.output.statusCode === 403 &&
         request.route.path === 'your_endpoint') {
        
        // your code here
      }
    
      return reply.continue();
    });

    【讨论】:

      猜你喜欢
      • 2022-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多