0

I am using API gateway with cognito for Authorize a POST method endpoint. if I am running it through Postman (JSON) it works great. BUT when I am running through a react app in CHROME I get Access to XMLHttpRequest at 'https://wjkgn56pb8.execute-api.us-east-1.amazonaws.com/test' from origin 'http://localhost:3000' 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.

Details over my API gateway API

  1. POST request with cognito authorizaer with expect a Authorization header

  2. The post request has lambda proxy that return the following header:

    "headers": 'Access-Control-Allow-Credentials':'true', 'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,X-Amz-Security-Token,Authorization,X-Api-Key,X-Requested-With,Accept', 'Access-Control-Allow-Methods':'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT', 'Access-Control-Allow-Origin':'', 'X-Requested-With':''

  3. OPTIONS method wihtout cognito authorizer

  4. I enable CORS on the endpoint.

result:

  1. without cognito on the POST it works -> i get content into my react app

  2. the moment I add cognito authIi get CORS error

  3. the part of react code I am running for this is:

    async function testClick() {
        try {
            const data = {
                clientId: user.userId,
            };
           const config = {
                headers: {
                    Authorization: user.token,
                },
           };
           const res = await axios.post(
               "https://wjkgn56pb8.execute-api.us-east-1.amazonaws.com/test",
               data,
               config
           );
           const messageData = res.data;
           console.log(messageData);
      } catch (err) {
           console.error(err);
        } }
    

I don't have any idea.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • Yes it works in Postman. Because postman is not a browser and doesn't care about CORS. `'Access-Control-Allow-Origin':''` you need a value for the header ... – derpirscher Aug 19 '23 at 13:03

1 Answers1

0

CORS (Cross-Origin Resource Sharing) is a security feature implemented by web browsers that restricts web pages from making requests to a different domain than the one that served the web page. The error you're seeing is a result of the browser enforcing this restriction.

You mentioned that you have enabled CORS on the endpoint. However, it looks like the 'Access-Control-Allow-Origin' header is not set correctly. This header should either be set to the origin of the web page making the request (e.g., 'http://localhost:3000') or to a wildcard ('*').

Here's what you can do to resolve the CORS issue:

  1. Set the 'Access-Control-Allow-Origin' Header: In the Lambda function that's connected to the API Gateway endpoint, make sure you set the 'Access-Control-Allow-Origin' header to the origin of your React app:

    "headers": {
        'Access-Control-Allow-Credentials':'true',
        'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,X-Amz-Security-Token,Authorization,X-Api-Key,X-Requested-With,Accept',
        'Access-Control-Allow-Methods':'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT',
        'Access-Control-Allow-Origin':'http://localhost:3000',
        'X-Requested-With':''
    }
    
  2. Enable CORS on API Gateway:

    • Navigate to your API in the API Gateway console.
    • Choose the specific resource and method for which you're facing the issue.
    • Choose "Enable CORS" from the "Actions" dropdown.
    • Confirm by selecting "Enable CORS and replace existing CORS headers".
    • Deploy your API.
  3. Check the OPTIONS Method:

    • Ensure that your API Gateway resource has an OPTIONS method.
    • This method should return the correct CORS headers. API Gateway can automatically generate this for you when you enable CORS.
  4. Cognito Auth and Pre-flight Requests:

    • When browsers make certain types of cross-origin requests, they send a "pre-flight" request using the OPTIONS method before making the actual request.
    • These pre-flight requests do not include any Cognito Authorization headers (or any other custom headers).
    • If your OPTIONS method or endpoint requires Cognito authentication, it will fail. Ensure that the OPTIONS method doesn't have any authentication.

By following these steps and ensuring the 'Access-Control-Allow-Origin' header is set correctly, you should be able to resolve the CORS error.

Piyush Patil
  • 14,512
  • 6
  • 35
  • 54