如何更改 API 网关响应

How to change API Gateway response

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

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

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

但是如果我不传递我的令牌,APIGateway 将 return 我

{
    "message": "Unauthorized"
}

在邮递员中我有状态码: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 以将 'Unauthorized' 错误更改为第三个代码示例中的错误。

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

允许获得如下回复:

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

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

  1. 转到 AWS 管理控制台中的 API 网关。
  2. Select 你的 API.
  3. 点击左侧的"Gateway Responses"
  4. Select "Unauthorized" 在网关响应列表中。
  5. Select "application/json" 在响应模板中单击 "Edit"。
  6. 根据您的要求更新响应模板正文。
  7. 点击"Save"。
  8. 重新部署您的 API。

添加到@svladimirrc,即使您没有适当的自定义授权程序,它也能正常工作,只需确保您的 API 网关配置为 link 的正确名称即可:

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'