Sometimes you may want to store your PDF, images, and doc files in Amazon S3 and restrict access to a specific domain or website. This is if you want to prevent people from linking directly to your s3 files to reduce usage costs or want to drive traffic to your web pages. You may also want to restrict AWS s3 files to premium members or provide them as digital downloads for sale
Procedure of restricting Amazon S3 bucket file download to a domain
To restrict Amazon s3 media file download and access to a specific domain then follow the steps below.
Step 1: Log in to your AWS account
Step 2: Then go to the Amazon S3 bucket
Step 3: Click on the main folder of the bucket
Step 4: At the top, you will see properties, permissions, metrics, management, and access points. Step 5: Click on permissions
Step 6: Copy and paste the JSON code below to the Bucket Policy form. Make sure that you have replaced dennokoech and exampledomain.com used below for demonstration with your s3 account username, domain URL, and bucket name
{
"Version": "2012-10-17",
"Id": "http referer policy example",
"Statement": [
{
"Sid": "Allow get requests referred by www.exampledomain.com and exampledomain.com.",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::491093115787:user/dennokoech"
},
"Action": "*",
"Resource": "arn:aws:s3:::dennokoech/*",
"Condition": {
"StringLike": {
"aws:Referer": [
"https://www.exampledomain.com/*",
"https://exampledomain.com/*"
]
}
}
},
{
"Sid": "Explicit deny to ensure requests are allowed only from specific referer.",
"Effect": "Deny",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::dennokoech/*",
"Condition": {
"StringNotLike": {
"aws:Referer": [
"https://www.exampledomain.com/*",
"https://exampledomain.com/*"
]
}
}
}
]
}
Step 7: Scroll to the bottom and the JSON file below to Cross-origin resource sharing. Change the domain URL to your website URL.
[
{
"AllowedHeaders": [
"Authorization"
],
"AllowedMethods": [
"GET",
"POST",
"PUT"
],
"AllowedOrigins": [
"https://exampledomain.com"
],
"ExposeHeaders": [],
"MaxAgeSeconds": 3000
}
]
The code above makes sure that your media files in s3 can only be downloaded from your whitelisted domains. If someone shares the same link on their website pages or social media, clicking on it will result in permission errors.
Leave a Comment