【问题标题】:Enable CORS DEFAULT 4XX/5XX for API Gateway in Cloudformation template在 Cloudformation 模板中为 API 网关启用 CORS DEFAULT 4XX/5XX
【发布时间】:2021-11-18 00:38:43
【问题描述】:

我正在为我的环境创建 AWS Cloudformation 模板,并尝试为 API Gateway 方法启用 CORS。回答问题#40292888 link to question #40292888 部分回答了我的问题。解决方案在 API 返回代码 200 时效果很好,但在测试 API 时我仍然收到 CORS 标头“Access-Control-Allow-Origin”丢失,但没有提供返回代码 403 Forbidden 的 api-key。我知道,如果您在从控制台启用 CORS 时选中 DEFAULT 4XX/5XX 它可以工作,我将如何在我的 cloudformation 模板中模拟它?

DEFAULT 4XX/5XX Api Gateway Console

谢谢,

【问题讨论】:

    标签: cors amazon-cloudformation api-gateway


    【解决方案1】:

    自己找到答案

    在通过控制台启用 CORS 时检查 DEFAULT 4XX/5XX 时,它会在您的 API 的网关响应下填充响应标头 key:value。

    这是在 CloudFormation 模板中模拟的代码(重复 5xx)。

    GatewayResponses4xx:
    Type: AWS::ApiGateway::GatewayResponse
    Properties: 
      ResponseParameters: 
        gatewayresponse.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
        gatewayresponse.header.Access-Control-Allow-Methods: "'GET,OPTIONS'"
        gatewayresponse.header.Access-Control-Allow-Origin: "'*'"
      ResponseType: DEFAULT_4XX
      RestApiId: !Ref BWTAPI
      # StatusCode: String
    

    谢谢。

    【讨论】:

      【解决方案2】:

      如果您使用 AWS SAM,这里有一个官方示例 https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-controlling-access-to-apis-customize-response.html

      Resources:
        MyApi:
          Type: AWS::Serverless::Api
          Properties:
            StageName: Prod
            GatewayResponses:
              DEFAULT_4xx:
                ResponseParameters:
                  Headers:
                    Access-Control-Expose-Headers: "'WWW-Authenticate'"
                    Access-Control-Allow-Origin: "'*'"
      

      【讨论】:

        猜你喜欢
        • 2017-03-10
        • 1970-01-01
        • 1970-01-01
        • 2015-05-19
        • 2023-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-30
        相关资源
        最近更新 更多