Prevent Hot link with S3 Bucket Policy (P1)

When your website goes live, Image/File hotlink is one issue that you must faced to.

There are many ways to prevent hotlink but the solution is depended on where is your file stored. Almost case in AWS cloud, you use S3 to store files so I will describe how to protect your website out of hotlink with 2 ways:

  1. S3 Bucket Policy
  2. Pre-Signed S3 URL

In this post, I will give example how to use S3 Bucket policy.

Firstly, go to the pros and cons.

Pros:

  • Easiest way
  • Fast to configuration

Cons:

  • Your bucket is still private bucket but it seems public bucket with defined domain.
  • If you want to private some file under current bucket out of accessing from defined domain, you need to define more policies. As default, defined domain can access all files inside current bucket.

Sample Policy:

{
  "Version": "2012-10-17",
  "Id": "",
  "Statement": [
    {
      "Sid": "allowMyDomains",
      "Effect": "Allow",
      "Principal": {
        "AWS": "*"
      },
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::BUCKET_NAME/*",
      "Condition": {
        "StringLike": {
          "aws:Referer": [
            "http://www.btuanexpress.net/*"
          ]
        }
      }
    },
    {
      "Sid": "denyAllOthersExceptMyDomains",
      "Effect": "Deny",
      "Principal": {
        "AWS": "*"
      },
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::BUCKET_NAME/*",
      "Condition": {
        "StringNotLike": {
          "aws:Referer": [
            "http://www.btuanexpress.net/*"
          ]
        }
      }
    }
  ]
}

As you can see in my sample policy, I only allow my domain http://www.btuanexpress.net and deny all others.

Part 2, Prevent hotlink with pre-signed S3 url

Leave a Reply

Your email address will not be published. Required fields are marked *