Cloud Unfold

unfolding the cloud trivia

API Gateway

Configuring CORS for an HTTP API with a $default route and authorizer

AWS Amazon API Gateway HTTP APIs come with built-in support for CORS, however configuring CORS on these APIs with $default route and Authorization can get a bit tricky, and usually results with CORS errors like no ‘Access-Control-Allow-Origin’ header. In this short blog, we will take a look at this configuration issue.

Solution

Create an HTTP API with $defaultroute, if you already have one, you can use it. Enable CORS and configure a greedy route like OPTIONS /{proxy+} without specifying an authorizer. This route will also need an integration to return CORS headers, to prevent a 404. For example, a sample Lambda function code to return the CORS headers for this route can be like this:

import json
def lambda_handler(event, context):
    return {
        "httpStatus": 200,
        "headers": {"Access-Control-Allow-Origin": "*"},
        "body": json.dumps(event)
    }

Why this works?

When you enable CORS and authorization for the $default route, there are some special considerations.

  • The OPTIONS method is only for preflight requests hence it neither expects nor requires authorization. However, the $default route on HTTP API catches requests for all methods and routes that you haven’t explicitly defined, including OPTIONS requests.
  • In HTTP APIs, the route OPTIONS /{proxy+} has higher priority than $default route. Thus setting the route this way, enables clients to submit OPTIONS requests without authorization, and hence the backend then returns CORS headers which takes care the CORS issues here.

For more information about routing priorities, see API Gateway HTTP API Routing API requests.

Testing

Once the API with the above OPTIONS /{proxy+} method is created, and deployed (if auto-deploy is not turned on), you can then test the API with the below curl command:

$ curl -X OPTIONS https://{api-id}.execute-api.{region}.amazonaws.com -I -H'Origin: https://example.com' -H'Access-Control-Request-Method: GET'

A sample curl response that you can expect would look something like this:

HTTP/2 200
date: Fri, 03 Mar 2021 10:44:59 GMT
content-type: application/json
content-length: 1165
access-control-allow-origin: https://example.com
access-control-allow-methods: GET,OPTIONS
access-control-allow-headers: access-control-allow-origin,authorization
access-control-max-age: 10
apigw-requestid: TayGXXXXXXXXXXXXXXXMZA=

For testing CORS on your API (HTTP or REST), you can use any online tools, like http://test-cors.org/ and https://resttesttest.com/.

You can find the a sample api export here. Further reading cors, AWS API Gateway HTTP APIs, and configuring cors with HTTP API $default route and authorization.

Was it helpful?

Tagged:
Just another lazy guy

LEAVE A RESPONSE

Your email address will not be published. Required fields are marked *

Related Posts