My API gateway with Lambda Integration works fine. However when I make an api key required it does not work. "Cross-Origin Request Blocked: The same Origin Policy disallows reading the remote resource at https://some-aws-api-gateway. (Reason: CORS header 'Access-Control-Allow-Origin' missing)."
A few findings:
Api gateway without api key X-Api-Key works for both POSTMAN and Browser. Api Gateway with api key only works for POSTMAN.
I have checked the headers multiple times, and they all are what they should be.
{
"Access-Control-Allow-Origin":"*",
"Access-Control-Allow-Credentials":"true",
"Access-Control-Allow-Methods":"GET,OPTIONS",
"Access-Control-Allow-Headers":"Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token",
"Content-Type":"application/json"
}
I decided to do an experiment. What I did was to remove api key requirement and changing "Access-Control-Allow-Origin":"*" to "Access-Control-Allow-Origin":"https://example.com/"). Now request from the browser had this error: CORS header 'Access-Control-Allow-Origin' does not match 'https://example.com' which is the intended result. This simply means to me that the headers I have set up in AWS Api Gateway are correct.
What I know so far:
"Access-Control-Allow-Origin":"*"with no api key required WORKS"Access-Control-Allow-Origin":"*"with api key DOES NOT WORK, ERROR: "Cross-Origin Request Blocked: The same Origin Policy disallows reading the remote resource at https://some-aws-api-gateway. (Reason: CORS header 'Access-Control-Allow-Origin' missing).""Access-Control-Allow-Origin":"https://example.com"(or any domain different from origin) with api key required DOES NOT WORK, ERROR: same as 2"Access-Control-Allow-Origin":"https://example.com"with no api key DOES NOT WORK, ERROR: CORS header 'Access-Control-Allow-Origin' does not match 'https://example.com'
If you notice, once the api key is required (2 & 3) you will get the same error message.
My question is why CORS fail when api key (X-Api-Key) is required, but pass when the api key is not required? This leads me to believe that the CORS headers on the Api Gateway is fine, however, the authentication process of validating the api key from browser request is where the problem lies. Why is the CORS header Access-Control-Allow-Origin missing on Api key required? I am wondering if the api key/headers needs to be encoded to a certain format or something.
var myHeaders = new Headers();
myHeaders.append("X-Api-Key", apiKey);
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow',
mode: 'cors',
credentials: 'include'
};
fetch("https://some-aws-api-gateway", requestOptions)
.then(response => response.json())
.then(result => console.dir(result))
.catch(error => console.log('error', error));