aws-samples / aws-samples/amazon-cloudfront-functions

anti-hotlinking with referer header

Open
#35 3 comments 2 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
533
Forks
76
PR merge metrics
No merged PRs in 30d

Description

Some users want to protect against hotlinking. A simple way is checking the value of `Referer` header with a CloudFront Functions function. The request will be rejected if the referer is not in the allow list.

There is a Lambda@Edge code example on Github, but no CloudFront Functions code.

The following is my CFF code. It has been tested in my environment and has been deployed in the production of a few customers. I was wondering if it is useful for this project?

```
//Escape "." character in a string
RegExp.escape = function(string) {
return string.replace(/\./g, '\\.');
};

function handler(event) {
var request = event.request;
var headers = request.headers;

var referrer = headers['referer'];

var response = {
statusCode: 403,
statusDescription: 'Forbidden',
headers: {
'content-type': { 'value': 'text/plain' }
},
body: 'Invalid referrer domain'
};

// Allow requests without the Referer header
if (!referrer) return request;
// Or block requests without the Referer header
// if (!referrer) return response;

var fqdn = referrer['value'].split('/')[2];

// Input your allowed domain name here
var allowedDomains = [
'domain1.com',
'*.domain1.com',
'domain2.com',
'*.domain2.com',
'sub.domain3.com',
'*.sub.domain3.com'
];

var allowedRegexList = [];

//Convert string to regex
for (var i=0; i

Contributor guide

Open the contributing guide

Research direction

Start with the supplied CloudFront Functions handler and compare its behavior with the referenced Lambda@Edge example and the repository’s existing example conventions. Done means the anti-hotlinking example is integrated in the expected form and its Referer allow-list behavior is documented or tested for allowed, disallowed, and missing headers.

Written by the indexing model from the issue text.

Assessment

Tech stack
aws, javascript
Domain
cloud, security
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.