Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Amazon S3 image CORS issue

' from origin 'http://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example.com' is therefore not allowed access.

I am using amazon cloudfront for CDN. can someone please tell me why i am still not able to see Access-Control-Allow-Origin:"*"?

MY S3 cors

enter image description here

like image 591
Venkatesh Avatar asked Apr 25 '18 12:04

Venkatesh


2 Answers

This is my setup, you need both edit the CORS in S3 as well in the CloudFront

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

I don't know if it's part of the protocol, but it's the only way I could set up for a CORS call

you also need to whitelist the Origin of your CDN behavior

like:

enter image description here

like image 111
balexandre Avatar answered Nov 09 '22 15:11

balexandre


I'm writing this answer cause I was stuck in the issue for almost a day.

Add CORS permission on AWS S3

  1. Open the specific bucket.
  2. Then click on the permission tab on the top enter image description here
  3. Then scroll to the last, and you will find the CORS configuration. Just click on edit. enter image description here
  4. Then paste the below configuration in
[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "GET"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": []
    }
]
  1. You can also add your custom domains inside AllowedOrigin

Remove cache from API call

I have done the above change but still, I was facing the same issue again and again. I fixed that by disabling the cache of the API. I was using fetch to call the s3 URL. Below is the code for it.

fetch(
    <s3 URL>,
    {
        method: 'GET',
        headers: { "Cache-Control": 'no-cache' },
    }
)
like image 35
Anand Tripathi Avatar answered Nov 09 '22 16:11

Anand Tripathi