CloudFront Functions Demo

When you click on the links below, a picture of a secret aircraft will be retrieved from S3, cached in CloudFront, and shown in your browser.

However, before downloading and forwarding the picture, CloudFront will run a CloudFront Function, which checks if your authorization is OK. This authorization is implemented (for demo purposes) in the query headers.

Download the picture without authorization: /secret/secret_aircraft.jpeg

Download the picture with an incorrect authorization: /secret/secret_aircraft.jpeg?secret=Wrong

Download the picture with the correct authorization: /secret/secret_aircraft.jpeg?secret=MySecret

Explanation

The URL for this page (cloudfunctions.demo.wlid.nl) points to a CloudFront distribution. This distribution has an S3 bucket as its origin. Most of the distribution is pretty standard, however the distribution has a "behaviour" for /secret/*. If anybody tries to download anything from this /secret directory, a ViewerRequest CloudFront Function is automatically invoked. This function is as follows:

function handler(event) {
    var request = event.request;
    
    if( request.querystring && request.querystring.secret && request.querystring.secret.value && request.querystring.secret.value == 'MySecret' )
    {
        delete request.querystring.secret;
        return( request );
    }
    
    var response401 = {
        statusCode: 401,
        statusDescription: 'Unauthorized'
    };
    return( response401 );
}

This function tries to locate the querystring parameter "secret" and checks if the value is "MySecret". If it is, it removes this parameter from the parameterlist and then returns the request. If a CloudFront Function returns such a request-type object, that's the indication to CloudFront to continue normal processing. However, if the "secret" querystring parameter is not present, or is not set to "MySecret", the function returns a response object with a 401 status code. Such a response will be sent to the client immediately, without any further processing by CloudFront.