Securing S3 with Origin Access Identity (OAI) via CloudFront
A Step by Step Approach
In my introductory AWS CloudFront article, it was explained how we can secure native and custom origins via CloudFront. Out of those methods, Origin Access Identity (OAI) can be used to secure a native S3 origin.
This article will discuss the OAI way of securing a native S3 endpoint in detail.
So lets dive in!
Make sure you are able to access both S3 bucket and the CloudFront distribution via web without any issue. What we are trying to implement here is blocking the S3 access for the public and restricting the access only through CloudFront.
Setting up OAI
There are two (02) basic steps while creating the OAI (See Figure 01).
- Add the OAI to the CF distribution origin.
- Update the existing S3 bucket policy related to OAI.
Step 1: Adding the OAI to the CF distribution
I assume the CF distribution is already created and the OAI will be added to the origin of the distribution.
P.Note that OAI can only be added to S3 origins only. If your origin is not a S3 origin then you will not see the OAI attributes on the console.
Task 1: Select the distribution that you have created before
Task 2: Select the origin of the distribution (The origin must be a S3 origin) and click “Edit”
Task 3: On the “Edit Origin” screen select the “Yes use OAI” option (See Figure 03).
Task 4: Once you select the “Yes use OAI” option make sure to create a new OAI or select one if you have already created before. Here we are going to use “Create new OAI” by clicking the “Create new OAI” button (See Figure 04).
Step 2: Updating the bucket policy
Task 1: After creating a new OAI, you can select the option of overriding the existing bucket policy with the save changes or doing it manually. Manual update is more suitable if you have a complex bucket policy only. Since we are not having a complex bucket policy we can choose the “Yes, update the bucket policy” option (See Figure 05).
Finally click “Save changes” button to save above settings.
Task 2: Once you click “Save Changes” at the origin, it will go and update the bucket policy with OAI changes (See Figure 06 — Sid “2”).
However, you can clearly see still the “s3”GetObject” statement (Allow ALL) is still remains and and it allows the bucket still to be accessed from the public Internet. You can try this by with the S3 public URL again and see.
Task 3: Delete the “s3:GetObject” statement from the bucket policy and keep the rest of the OAI related statement as it is. This will ensure only the OAI is allowed to access this bucket, which means only the CF distribution is allowed to route the Internet traffic (See Figure 07).
Now it is time to see whether you can access the S3 via public Internet. If all okay, you will get the following error message (See Figure 08).
Meantime, you need to try the CF URL or the domain URL, which CF distribution attached to. That link will sure lead to the correct website without any problem.