Keeping Simple Simple Storage Service (S3) safe within the VPC by preventing public access and only allowing access through Cloudfront is key to securing your information in AWS Cloud.
First, we have to make sure the S3 bucket doesn’t have any Public access to it and we need to create a special type of identity called Origin Access Identity (OAI). Once we create this Identity we can associate this with CloudFront distribution which means the edge locations of CloudFront will gain this Identity to access S3 or other AWS resources. Next, we can then adjust the S3 bucket policy to Explicit allow that OAI and Implicit deny all other access from S3.
To create OAI we need to go to CloudFront Distribution and select the distribution that you have hosted in Cloudfront for S3 and go to Origins and Origin Groups Tab.
Currently, it is S3 origin Type, Edit The Origin and select Restrict Bucket Access to Yes.
Then create a New Identity and you can provide comments as per your naming standards but I am leaving it as default for this demo.
Change to Grant Read Permission on Bucket to Yes, Update Bucket Policy. We can do this manually later on but for this demo purposes, we want to make things simple. Then press Yes Edit to save the changes. (Make sure you have not already manually blocked public access.)
If we go and check S3 permissions we can see Cloudfront OAI has created permission in the bucket policy.
Now we need to edit the bucket policy and delete the top component that allows public access and Save changes so that only Cloudfront distribution will have access. The policy will look similar to image displayed above and will not have any public access to S3.
Now if you try to load an object or a static website from S3 URL then it will show Access Denied but if we use Cloudfront Domain Name then it will work.
When you use Cloudfront Domain name then the website or the object in S3 is successfully accessible.
This means our S3 is not allowed from public access but only through Cloudfront Distribution which is the perfect way for securing your S3 buckets within a secure environment.