3

I'm creating AWS Cloudformation template for my environment and I try to enable CORS for API Gateway method. Answer to question #40292888 link to question #40292888 partially answered my question. Solution works great when API return code 200 but I still receive CORS header “Access-Control-Allow-Origin” missing when testing the API without providing the api-key which return code 403 Forbidden. I know that if you check DEFAULT 4XX/5XX when enabling CORS from the console it works, how would I simulate that in my cloudformation template?

DEFAULT 4XX/5XX Api Gateway Console

Thank you,

2 Answers2

6

Found answer myself

When checking DEFAULT 4XX/5XX when enabling CORS through the console it populates response header key:value under Gateway Responses for your API.

Here is the code to simulate that in the CloudFormation template (duplicate for 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

Thanks.

2

If you use AWS SAM, here is an official example 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: "'*'"
Tom TANG
  • 21
  • 1