Search code examples
javascriptamazon-s3corsamazon-cloudfront

Amazon S3 + CloudFront CORS issue


We are using Amazon S3 + CloudFront for serving JSON files. We uploaded two files lets consider as j1.json and j2.json. Both files initially responding valid CORS headers in the response, but when running invalidation on j2.json its header responses changed, and we are facing CORS issue.

CORS permissions set on S3 bucket -

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

Response headers for j1.json

enter image description here

Response headers for j2.json enter image description here

Both JSON files in the same bucket, but j2.json response missing these headers

Access-Control-Allow-Methods →GET
Access-Control-Allow-Origin →*
Access-Control-Max-Age →3000

We tried deleting and uploading again object, it's not responding CORS headers in the response. What is the possible reason for this issue? And how to solve it?


Solution

  • Before S3 will return correct CORS response headers, it needs to see that the request is a CORS request.

    CloudFront, by default, forwards as few headers to the origin as possible, since the fewer headers the origin requires, the better your cache hit rate will tend to be (because any header not sent to the origin can't cause the origin to vary its response, thus all responses to a given request would be expected not to vary, and thus be cacheable). But for a CORS request, we need S3 to see some specific headers so it can react accordingly.

    In the Cache Behavior configuration, you'll need to whitelist these 3 request headers for forwarding to the origin.

    Access-Control-Request-Headers
    Access-Control-Request-Method
    Origin
    

    Once this change completes, an invalidation might also be appropriate.