Basic Auth For CloudFront Distributions

Basic Auth For CloudFront Distributions
Photo by Markus Spiske / Unsplash

Introduction

Amazon CloudFront is a content delivery network (CDN) service part of AWS. CloudFront securely distributes static and dynamic web content, video and data to users worldwide at high speed.

CloudFront provides fast load times by placing content in the closest location. (Edge Server) This gives users a faster and smoother user experience. CloudFront caches data at many different edge locations, providing users a faster and more reliable service.

Problem

Do you want to protect your webpage from unauthorized access? If your answer is yes, then you need to do it yourself. There are no pre-defined functions for that.

What is Basic Authentication?

Basic Authentication is a method used to authenticate a user by providing a username and password in plain text format. It is one of the simplest authentication mechanisms used on the web and is widely supported by web servers and web applications.

Solution

Let's create a basic lambda function. To do this, just follow the steps below:

  • Open the Lambda dashboard, then click Create Function button.
  • Choose Author from scratch
  • Type the Function Name
  • Select Node.js 18.x as runtime.
  • Click Create Function button.

Here is our basic Auth Code:

exports.handler = async (event) => {
    let isAllowedAccess = false;
    const request = event.Records[0].cf.request;
    if (request && request.headers && request.headers.authorization) {
        const basicAuthHeader = request.headers.authorization[0].value;
        const authString = 'Basic ' + new Buffer('username' + ':' + 'password').toString('base64');
        isAllowedAccess = (basicAuthHeader === authString)
    }
    
    if(!isAllowedAccess){
        const response = {
            status: 401,
            body: JSON.stringify('Access Denied!'),
            headers: {
                'www-authenticate': [{key: 'WWW-Authenticate', value: 'Basic'}]
            },
        };
        return response;
    } else {
        return request;
    }
};

Don't forget to change username & password in the sample code block.

Now you need to do one more thing, you need to change your CloudFront Distribution behavior.  

  • Open your CloudFront Dashboard and select the distribution.
  • Click the Behaviors tab.
  • Select your entry and click the Edit button.
  • Scroll to the bottom, and write your function arn to the Viewer request.
  • Click Save Changes.

If you open your webpage, you should see the basic auth there.

Conclusion

Today, we learned how to apply a simple security measure to the pages we publish with the Cloudfront service. We have now closed our test pages to unauthorized access.

See you in the next article.  👻