CORS in S3 bucket

Cross Origin Resource Sharing (CORS)

Diagram:

Background

Hosting web site and images are sourcing from S3 bucket. Website is Coded in Java Script is using images from different bucket as source bucket. A browser will block Java script requests & gives error or different origin. In diagram, www.example.com is configured in EC2 where images are sourced from S3 bucket. Images are sourced with static website www.xyz.com & www.abc.com .

Www.example.com shows images from www.xyz.com where www.abc.com images are blocked.

The reason is CORS enabled and configure in www.xyz.com bucket.

Now one more case, we you have host website on S3 but fonts of website is loading from different s3 bucket. In this scenario as well get error of different origin.

Cross Origin Resources sharing enable will resolve the error.

How to use

CORS can be configure through AWS console , AWS SDK for JAVA,PHP & .NET .

Here we are going to discuss CORS configuration through AWS console.

Configure.

Step 1.

Create bucket “tom789” & “jerry456”

 

Bucket permission needs to be “PUBLIC” for both buckets.

 

Step 2.

 

Enable static website on bucket “tom789”

 

Upload index.html. Index.html can be uploaded through aws console & aws cli. Here I have

used AWS CLI.

[jaymin@localhost ~]$ cat index.html

<script src=”http://code.jquery.com/jquery-1.12.0.min.js”></script>

<div id=”loaded_file”></div>

<script>

$(function() { $(“#loaded_file”).load(“msg.html”);

});

</script>

 

Upload msg.html on bucket “jerry456” make msg.html public.

[jaymin@localhost ~]$ vim msg.html

“Cross over region resources”

 

[jaymin@localhost ~]$ aws s3 cp index.html s3://tom789

upload: ./index.html to s3://tom789/index.html

Step 3.

 

Try to access static web site endpoint of bucket “tom789”. It will not show msg.html & show

error in page.

 

Step 5

 

Go to bucket properties of bucket “jerry456” add CORS configuration

 

 

Step 6

 

Access static endpoint of bucket “tom789” it will show msg.html

 

Note: make sure both buckets and index.html & msg.html are public.

 

I hope you find this blog helpful.

Jaymin Pandit.
AWS Solution Architect ,
Electromech Corporation,

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*