For an S3 bucket to have public read access, we need to change three configurations - disabling the Block public access
section, adding access permissions in Bucket Policy
section and allow all HTTP requests in the Cross-origin resource sharing (CORS)
section.
Steps to allow public read access in S3
1. Disable the "Block all public access" setting
Go to the S3 bucket that you want to give the public access to. From there, click on the Permissions
tab shown below. In the section, "Block public access (bucket settings)"
click on the "Edit" button
Uncheck the "Block all public access"
checkbox and hit save
2. Adding read rights to the bucket policy
Now, we need to add the required bucket policy for public access. If you scroll down in the Permissions
tab, you will see the Bucket Policy
section. Click on the "Edit" button.
Now, add the following JSON data into the policy text area. This will authorise us to retrieve the objects like files, images, etc in the specified bucket resource.
{
"Version": "2012-10-17",
"Statement": [
{
"Principal": "*",
"Effect": "Allow",
"Action": [
"s3:GetObject"
],
"Resource": [
"arn:aws:s3:::YOUR_BUCKET_NAME/*"
}
]
}
Once the bucket policy has been added, the Bucket Policy
section will look like the below image.
3. Adding Cross-origin resource sharing (CORS) rights to all origins
Now to allow the bucket to be accessible from any IP address through an HTTP request, we need to add the following CORS policy to the Cross-origin resource sharing (CORS)
section of Permissions
.
[
{
"AllowedHeaders": [
"Authorization",
"Content-Length"
],
"AllowedMethods": [
"GET"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": [],
"MaxAgeSeconds": 3000
}
]
Scroll down to the CORS policy section and click the "Edit" button.
Add the above-given policy to the text area and hit save. Once the policy has been added the Cross-origin resource sharing (CORS)
section will look like the below image.
This should give the public access to every object inside the specified bucket. And there will be an indication as shown below to indicate that the bucket is publically accessible.
Don't worry, by the time you are reading this, this bucket won't exist :D
Let's test whether the policy is working or not.
Testing the public access permission
Go to the Objects
tab in your bucket. If no object is present, then upload a file or an image. Select the object in the bucket and click on "Copy URL"
like shown below.
Visit the copied URL in your browser and see if it is accessible or not. If you followed every step, the policy we added should give the public read access to this bucket.
I hope this helped you, visit my blog to see more interesting articles. I will see you at the next one.