Enable CORS DEFAULT 4XX/5XX for API Gateway in Cloudformation template

Viewed 587

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 Answers

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.

Related