2
votes

I have a Lambda function integrated with API Gateway with CORS enabled. I'm using the LAMBDA_PROXY integration, so I know I must specify the Access-Control-Allow-Origin header in my response in the Lambda function. However, I only want to allow cross resource sharing from a specific domain (www.example.com).

Lambda Function -

'use strict'
module.exports.handler = (event, context, callback) => {
  const response = {
    statusCode: 200,
    headers: {
      "Access-Control-Allow-Origin": "https://www.example.com"
    },
    body: JSON.stringify({
      message: 'Go Serverless v1.0! Your function executed successfully!'
    }),
  };

  callback(null, response);
};

When I perform a test GET request (from the API Gateway console) it returns a successful (200) response. I would expect because I'm invoking the endpoint from the AWS Api Gateway console and not from https://www.example.com the endpoint should have returned a non-200 status code.

I can see the Access-Control-Allow-Origin header in my response - enter image description here

Why am I getting a 200 status code if my origin domain is not https://www.example.com??

Also, I've tried making an Ajax call from a website statically hosted website in S3. I'm still getting the 200 response and the JSON data even though I'm clearly not making the call from www.example.com.

EDIT:

I ended up recreating the resources just to add a live example to this question.

When I click on the API endpoint directly, it allows me to get the JSON data back (I'm using Google Chrome 64.0.3282.186 and FireFox 58.0.2).

https://w69y8dk663.execute-api.us-east-1.amazonaws.com/dev/api/status

However, when I make an Ajax request from a statically hosted s3 website, I get the error.

http://test-cors-ajax.s3-website-us-east-1.amazonaws.com/

I tested the ajax yesterday and it was letting me get the JSON data back, something must have been getting cached somewhere (running old code that didn't have the allow-access-origin header). Anyways, it looks like it's functioning as expected.

I do find it interesting that my browser let's me directly hit the endpoint without throwing the CORS error. Thank you for your input.

1
CORS isn't designed to restrict, it's designed to allow the browser to decide. A 200 is normal, but can you actually access the Ajax response?Michael - sqlbot
@Michael-sqlbot - Turns out I'm not able to make the Ajax request. See my edit above for more info.Chris Diggs

1 Answers

3
votes

CORS isn't a mechanism for controlling how the server behaves; it's for telling the browser how to behave.

The request will succeed (i.e. return 200), but the Same Origin Policy will prevent foreign sites from reading the response unless there's a CORS directive allowing it.