Search code examples
amazon-s3amazon-cloudfront

Restrict Amazon S3 to CloudFront and http referrer


I have an Amazon S3 REST endpoint for images and file assets. I want the S3 bucket only accessible by CloudFront and the website accessing the images (using http referrer).

This is my bucket policy so far:

{
    "Version": "2008-10-17",
    "Id": "PolicyForCloudFrontPrivateContent",
    "Statement": [
        {
            "Sid": "1",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity XXXXXXXXXXXX"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::<DOMAIN>/*",
            "Condition":{
                "StringLike":{"aws:Referer":["http://<DOMAIN>/*"]}
            }
        }
    ]
}

But once I apply the policy, the images are not accessible on the website.

Is this possible to do?


Solution

  • CloudFront strips Referer header by default so S3 will not see it.

    https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/RequestAndResponseBehaviorCustomOrigin.html

    You need to Whitelist the Referer header in CloudFront and invalidate the cache to see if it works.