【问题标题】:How to change API Gateway response如何更改 API Gateway 响应
【发布时间】:2020-06-23 18:25:41
【问题描述】:

我有一个 aws ApiGateway 来验证我的令牌并将请求传递给 lambda。

当我收到来自 lambda 的错误时,APIGateway 响应是

{
    "statusCode": 500,
    "error": "Internal Server Error",
    "message": "..."
}

但是如果我不传递我的令牌,那么 APIGateway 会返回给我

{
    "message": "Unauthorized"
}

在邮递员中我有 statusCode: 401。

我希望它是怎样的:

{
    "statusCode": 401,
    "error": "Unauthorized"
}

我使用 serverless.yml 来部署:

functions:
  index:
    handler: dist/index.handler
    events:
    - http:
        cors: true
        path: '/'
        method: any
        authorizer:
          type: COGNITO_USER_POOLS
          authorizerId:
            Ref: ApiGatewayAuthorizer

请告诉我如何更改我的 serverless.yml 以将“未授权”错误更改为第三个代码示例。

【问题讨论】:

    标签: amazon-web-services api amazon-cloudformation aws-api-gateway serverless


    【解决方案1】:

    添加到@svladimirrc,即使您没有自定义授权方也可以使用,只需确保您的 API 网关的正确名称配置为链接到:

    resources:
      Resources:
        ApiGatewayRestApi:
          Type: AWS::ApiGateway::RestApi
          Properties:
            Name: ${self:provider.stage}-${self:service}
        InvalidApiKeyGatewayResponse:
          Type: 'AWS::ApiGateway::GatewayResponse'
          Properties:
            RestApiId: 
              Ref: 'ApiGatewayRestApi'
            ResponseType: INVALID_API_KEY
            ResponseTemplates:
              application/json: "{\"success\":false,\"message\":\"Invalid API key\"}"
            StatusCode: '401'
    

    【讨论】:

      【解决方案2】:

      您可以通过修改网关响应来实现此目的。

      1. 在 AWS 管理控制台中转到 API Gateway。
      2. 选择您的 API。
      3. 点击左侧的“Gateway Responses”。
      4. 在网关响应列表中选择“未授权”。
      5. 在响应模板中选择“application/json”并点击“编辑”。
      6. 根据您的要求更新响应模板正文。
      7. 点击“保存”。
      8. 重新部署您的 API。

      【讨论】:

        【解决方案3】:

        尝试实现这个: https://github.com/SeptiyanAndika/serverless-custom-authorizer:

        允许得到如下响应:

        {
          "success":false,
          "message":"Custom Deny Message"
        }
        

        【讨论】:

          猜你喜欢
          • 2020-12-16
          • 2021-10-19
          • 1970-01-01
          • 1970-01-01
          • 2018-06-09
          • 1970-01-01
          • 2019-11-07
          • 2017-08-08
          • 2016-04-16
          相关资源
          最近更新 更多