Member-only story
How to Restrict Access to Your CloudFront Distribution With Basic Authentication
Using AWS Lambda@Edge
When developing a web application, you may decide to serve the landing page along with every static file through a CDN for better performance. CloudFront is a CDN offered by AWS that allows you to serve your content from different sources, known as origins, like S3 or a Load Balancer. Your application’s static files or dynamic data will be served through these origins to your users.
The Issues
But during the development process of the application, you would need to host on AWS. Besides experimenting with different services on AWS, you would also need to create a staging or testing environment that can only be accessed by certain users.
In addition to that, as you may know, Google is constantly crawling the web and indexing the websites for user search queries, so you probably don’t want your staging environment to be indexed by Google and thus available to the world.
The Solution
In that case, you would need a way to protect the content served through the CDN, and you can do that with an authentication method known as Basic Authentication. It is an authentication scheme built into the HTTP protocol that allows the users to access secured content by sending requests with a special Authorization
header that contains a base64
encoded version of a username and password to log in.
An example is provided below:
Authorization: Basic ZGVtbzpwQDU1dzByZA==.
This is the authorization dialog you get when you try to access a Basic Authorization-protected source:
Enter Lambda@Edge
There is no direct method to apply Basic Authorization directly on CloudFront. However, it can be done by utilizing Lambda@Edge, which is a feature that allows you to execute logic before a request or after a response to your CloudFront distribution by adding different headers or checking the presence and validity of other request headers.
In our case, what you need is this: “Check whether a request made to the distribution contains the Authorization
header, and if it does, whether the…