Setup CORS For Amazon API Gateway via AWS CDK

The guide demonstrates how to setup CORS for the Amazon API Gateway proxy and non-proxy Lambda integrations via AWS CDK

Tuesday, August 3, 2021

Lambda Non-Proxy Integration

The first step is to set up the OPTIONS method for the resource for which you want to set up CORS. That can look for example like

Your resource MyCorsResource will now have the OPTIONS method allowing access from specified origins. allowedHeaders code fragment is a demonstration of how you can allow non-standard headers, e.g. x-api-key in case your API accepts the API key from the headers. You can also specify allowed methods, see the link at the end of the article for the CDK documentation.

The second step is to return the access-control-allow-origin header from the response of your resource's API method itself. At the time of writing this guide, I did not figure another way to achieve it other than to mirror what is done under the hood by CDK for the OPTIONS method. The origin resolution is done via the response mapping template. When you open the generated CloudFormation template for the OPTIONS method, you will see something like

I added the indentation and replaced \n with newlines for the clarity. You can generate the very same response mapping template addition to your response mapping template for the target method. A simple CDK code helper to achieve it can look like

The mapping template addition is then used on your integration responses such as

Lambda Proxy Integration

The first step is the same as for non-proxy integration, i.e. you specify the CORS settings on the OPTIONS method of your resource. Taking the example from non-proxy integration

The second step, to return the access-control-allow-origin header from the response of hour resource's API method is done on the level of your lambda handler, as there is no response mapping template in the proxy integrations. The solution I ended up with was storing the allowed origins in the SSM, receiving them in my lambda handler, and comparing them with the origin header of the request. Proxy integration request and response needs to follow the AWS contract, important bits for the CORS setup are

The C# code snippet to resolve the CORS response headers can look for example like

Further Reading