Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configuring CORS for API Gateway in SAM/CloudFormation/Swagger

I followed the example from here which includes a swagger file for configuration of CORS + SAM. It seems like I still get CORS error unless I add CORS headers manually into each function:

callback(null, {
    statusCode: '200',
    headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token',
        'Access-Control-Allow-Methods': 'OPTIONS,GET,POST,PUT,PATCH,DELETE'
    },
    body: JSON.stringify({message: "Hello world"})
});

Is this correct? Or am I doing something wrong?

like image 439
Jiew Meng Avatar asked Aug 26 '17 04:08

Jiew Meng


People also ask

How do I enable CORS in Sam template?

To enable CORS for the Lambda proxy integration, you must add Access-Control-Allow-Origin:domain-name to the output headers. domain-name can be * for any domain name. Save this answer.

How do I fix the CORS issue in AWS API gateway?

To resolve a CORS error from an API Gateway REST API or HTTP API, you must reconfigure the API to meet the CORS standard. For more information on configuring CORS for REST APIs, see Configuring CORS for a REST API resource. For HTTP APIs, see Configuring CORS for an HTTP API.


2 Answers

All AWS docs suggest you need to specify those 3 headers in every API Gateway resource and return them in every function response that will support CORS, you can see they had to add those 3 headers to the 2 API Gateway endpoints defined in the example project's swagger.yaml file.

The Github sample you mentioned is using what is called a proxy resource in API Gateway, which basically an API Gatewaty route that will match any request made to the api and trigger the proxy lambda function with the request's parth, method ... etc. You can learn more about how it works here.

Are you open to trying something like serverless which can help you better organize your lambda functions just like SAM does. It also support CORS.

like image 100
mostafazh Avatar answered Nov 15 '22 09:11

mostafazh


I know it is tedious task to add all these to your Swagger JSON for all the methods.

            "headers": {
            "Access-Control-Allow-Origin": {
                "type": "string"
            },
            "Access-Control-Allow-Methods": {
                "type": "string"
            },
            "Access-Control-Allow-Headers": {
                "type": "string"
            }
        }

I have created a utility in Java which automatically adds these headers to your Swagger JSON. You can run it before importing it to API Gateway.

https://github.com/anandlalvb/SwaggerToAPIGateway

like image 44
binary Avatar answered Nov 15 '22 09:11

binary