How do I use my CloudFront distribution to restrict access to an Amazon S3 bucket?

Last updated: 2020-05-28

I want to restrict access to my Amazon Simple Storage Service (Amazon S3) bucket so that objects can be accessed only through my Amazon CloudFront distribution. How can I do that?

Resolution

Important: Before you begin, be sure that the Amazon S3 origin of your CloudFront distribution is configured as a REST API endpoint (AWSDOC-EXAMPLE-BUCKET.s3.amazonaws.com). This resolution doesn't apply to S3 origins that are configured as a website endpoint (AWSDOC-EXAMPLE-BUCKET.s3-website-us-east-1.amazonaws.com).

Create a CloudFront origin access identity (OAI)

1.    Open the CloudFront console.

2.    From the list of distributions, choose the distribution that serves content from the S3 bucket that you want to restrict access to.

3.    Choose the Origins and Origin Groups tab.

4.    Select the S3 origin, and then choose Edit.

5.    For Restrict Bucket Access, select Yes.

6.    For Origin Access Identity, select either Create a New Identity or Use an Existing Identity.

7.    For Grant Read Permissions on Bucket, select Yes, Update Bucket Policy.
Note: This step updates the bucket policy of your S3 origin to grant the OAI access for s3:GetObject.

8.    Choose Yes, Edit.

Review the bucket policy

1.    Open the Amazon S3 console.

2.    From your list of buckets, choose the bucket that's the origin of the CloudFront distribution.

3.    Choose the Permissions tab.

4.    Choose Bucket Policy.

5.    In the Bucket policy editor, confirm that you see a statement similar to the following:

{
	"Sid": "1",
	"Effect": "Allow",
	"Principal": {
		"AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity EAF5XXXXXXXXX"
		},
	"Action": "s3:GetObject",
	"Resource": "arn:aws:s3:::AWSDOC-EXAMPLE-BUCKET/*"
}

This is the statement that CloudFront adds to your bucket policy when you select Yes, Update Bucket Policy as part of the OAI setup.

6.    Review your bucket policy for any statements with "Effect": "Deny" that prevent access to the bucket from the CloudFront OAI. Modify those statements so that the CloudFront OAI can access objects in the bucket.

7.    Review your bucket policy for any statements with "Effect": "Allow" that allow access to the bucket from any source that's not the CloudFront OAI. Modify those statements as required by your use case.

Note: If you use object access control lists (object ACLs) to manage permissions, then you must also review the object ACLs to be sure that those files aren't accessible outside of the CloudFront OAI.

After you restrict access to your bucket using the CloudFront OAI, you can optionally add another layer of security by integrating AWS WAF.