user3732456
user3732456

Reputation: 33

Cannot query AWS API Gateway using API Key and CORs

I'm almost complete with a new web app, however, I'm getting a 403 error from AWS's API Gateway due to a CORs issue.

I'm creating a Vue app and using Vue's axios library. CORs is enabled and the request works with API Key Required option turned off in AWS's API Gateway by sending the following:

    axios
      .get('My-URL-Endpoint',{headers: {})
      .then(response => (this.passports = response.data ));

When I turn on API Key Required functionality inside AWS's API Gateway. It works when I use Postman along with including x-api-key: My-API-Key. However, using Vue's axios it does not work and returns error 403:

    axios
      .get('My-URL-Endpoint', {headers: { 
        'x-api-key': 'My-API-Key'
      }})
      .then(response => (this.passports = response.data ));

My first instinct is that the problem is related to how Axios is sending the request through the browser. From what I can gather it looks like the pre-flight check is failing because I am receiving the following error within the browser:

Access to XMLHttpRequest at 'My-URL' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Sure enough it looks like there is no access-control-allow-origin key in the response. So I added access-control-allow-origin to the response of the 403 message and got a new error "It does not have HTTP ok status"

I've been trying nearly everything to get this to work! I came across stackoverflow answer where it seems like the person was suggesting that API Key Required Key functionality can't work with CORs. This kind of seemed like that cannot be true. It would be a pretty crippling restriction.

So my question is how to get the browser's pre-flight check to work along with CORs and API Key capability inside AWS's API Gateway?

Thank you!

Upvotes: 0

Views: 2192

Answers (1)

Arun Kamalanathan
Arun Kamalanathan

Reputation: 8583

If you have enabled cors on your api gateway, the next place to look is the application code such as lambda. Make sure the Lambda is returning the correct cross origin headers in both successful and failure scenarios.

First of all you can check if the request is reaching the lambda from the cloud watch logs. Another way to check this is to temporarily point the Api gateway target to the Mock end point.

If the mock endpoint works, then the problem is the application code. otherwise the problem is in your api gateway end point.

Also note that any headers you use should be white listed in the Access-Control-Allow-headers section when you enable to cors for your method/resource.

Upvotes: 2

Related Questions