Enabling CORS on API Gateway Resources
Introduction
CORS stands for Cross-origin resource sharing. It is a set of standard HTTP headers used to restrict the access of web resources from other domains. In the web app security model, this is called same-origin policy, and it's supposed to avoid cross-site scripting (XSS) attacks. Browsers will not fetch the requested resources unless the corresponding server attaches the required HTTP headers in the OPTIONS call (or GET method).
The API Gateway will not automatically add these headers, but it provides a very user-friendly wizard. In this Lab Step, you will see how to enable CORS on our API Gateway resources. Keep in mind that you need to enable it on each resource.
Instructions
1. Select the /items API Resource and click on Actions > Enable CORS:
This starts a wizard that allows you to configure which headers to serve and which headers are allowed. A minimal CORS integration would require at least the Access-Control-Allow-Origin header. If its value is *, every domain will be allowed to fetch this resource. The API Gateway will automatically allow GET and OPTIONS methods, plus all the default headers used by AWS services (Content-Type, X-Amz-Date, X-Api-Key, X-Amz-Security-Token and Authorization). This will guarantee that you can use API Keys, Basic Authentication and IAM tokens.
2. Click Enable CORS and replace existing CORS headers to enable CORS with the default values:
An additional confirmation popup will follow, with a list of all the required operations that will be executed for you:
Note that there is not too much magic going on here. The API Gateway will simply configure itself to enable CORS on the specified resource, by creating a new OPTIONS method and all the required Method Response and Integration Response options.
3. Click Yes, replace existing values.
You can always customize or remove this integration afterward or even do it yourself manually.
4. Repeat the above instructions except using the /items/{ID} resource to enable CORS for it.
After enabling CORS on both resources, your API should look like this:
Note: The OPTIONS method will be invoked by the browser as a preflight request, before the actual GET request. If the OPTIONS call doesn't succeed, browsers won't even issue your GET request.
Summary
In this Lab Step, you used the API Gateway wizard for enabling CORS on both of your API resources. CORS enhances the security of web apps.