Hello learners, in this article we will learn how we can deploy an S3 bucket and then protect S3 bucket with a password authentication mechanism for security purposes. With that in mind, let’s get started.
Overview on S3 Bucket
Amazon S3 Bucket is a publicly available cloud storage service which enables users to store any amount of data at any time or place giving developers high scalability, reliability and inexpensive data storage. S3 also provides very easy management features to organize data for websites , mobile apps , backups etc.. There are various storage classes of S3 designed for various purposes , so the users can select any storage class they need and pay the cost according to the respective class.
Overview on CloudFront
Amazon Cloudfront operated by Amazon Web Services is a global CDN Service that is used to securely deliver data, videos, applications, and APIs to customers globally with low latency, high transfer speeds, all within a developer-friendly environment. Cloudfront is available with many edge locations in each country to provide fast and low latency access to all its users. Cloudfront can also be integrated seamlessly with S3 , Load balancers and EC2. Cloudfront also provides caching capability through which users can load the websites at a faster rate.
What is Lambda ?
AWS Lambda is a serverless, event-driven compute service that lets you run code for virtually any type of application or backend service without provisioning or managing servers.Lambda users can create functions in their comfortable language and upload them to Lambda which will run them in the manner they need efficiently and flexibly.Lambda can be used for various tasks but lambda is actually most used for completing individual tasks in a short time.You can trigger Lambda from over 200 AWS services and software as a service (SaaS) applications, and only pay for what you use.
Since, we have got the basics covered. Let’s protect s3 buckets & get our hands dirty!
Step 1 : Create S3 bucket
1. Go to your AWS Management Console and go to Amazon S3 and click on Create bucket.
2. Now, enter the bucket details:
Bucket name : Your bucket name as you want
AWS Region : Select an AWS region located near to you for better latency
3. Leave all public access and all the other options default or if you need something for your bucket then do enable them as per your needs
4. Now go to Objects where you can upload all the files of your S3 static website, so click on Upload to upload all the website files to the S3 bucket.
5. Here is my sample index.html file
<h2>Hello World</h2>
6. We have successfully created an S3 bucket and have an index file which we want to protect with a password.
Step 2 : Create a Cloudfront Distribution
1. Go to the CloudFront Dashboard using Search bar and click on Create Distribution.
2. Choose the Origin Domain as the Amazon S3 bucket and create a new OAI identity and update the bucket policy.
3. Enter the root document as index.html and leave all the other options default and click on Create
4. The CloudFront distribution was created successfully and we have received a cloudfront endpoint now. You can collect the same as shown below, we will have to use this in our next steps.
Step 3 : Create a Lambda Function
1. Go to the Lambda dashboard using Search bar and click on Create Function
2. Select the type as Blueprint and search for “cloudfront” , select cloudfront-response-generation from the search results and click on Configure
3. On the following screen name your function and select the “Create the new role from AWS Policy templates”
4. Click on Create Function and you will now be asked about the cloudfront details. Choose the Cloudfront distribution you have created , leave the cache behavior as *. Select Viewer Request for the Cloudfront Event.
5. Finally click on Deploy and the lambda function gets created.
Step 4: Update the code of Lambda function to protect S3
1.Go to the Code Tab and paste the following code
'use strict';
exports.handler = (event, context, callback) => {
// Get request and request headers
const request = event.Records[0].cf.request;
const headers = request.headers;
// Configure authentication
const authUser = 'YOUR USERNAME';
const authPass = 'YOUR PASWORD';
// Construct the Basic Auth string
const authString = 'Basic ' + new Buffer(authUser + ':' + authPass).toString('base64');
// Require Basic authentication
if (typeof headers.authorization == 'undefined' || headers.authorization[0].value != authString) {
const body = 'Unauthorized';
const response = {
status: '401',
statusDescription: 'Unauthorized',
body: body,
headers: {
'www-authenticate': [{key: 'WWW-Authenticate', value:'Basic'}]
},
};
callback(null, response);
}
// Continue request processing if authentication passed
callback(null, request);
};
2. After pasting the following code, click on Deploy which is just above it for the changes to be saved.
3.After the code changes are done, go to Actions which is at the top of Lambda Dashboard and click on Deploy to Lambda Edge.
4.Now create new Cloudfront trigger and leave the Cache behavior as * and Cloudfront event as Viewer request and click on Deploy.
5.Wait 5 minutes for the deployment to be completed and visit your cloudfront endpoint.
6.You should see that your cloudfront endpoint now asks for an username and password.
FAQ
Who can use this Password Mechanism ?
Any small websites or startups can use this kind of basic password authentication mechanism to protect their sensitive files or any exclusive content which they want only the paid users to have access to. If you are an enterprise , then you should look out for AWS Cognito which supports SSO Authentication.
How to Clear Cloudfront Cache ?
Go to your Cloudfront distribution and navigate to the Invalidations tab. Click on Create and give the name of the file for which you want the cache to be cleared.Once the invalidation is completed , the cache for that file will be removed.
Conclusion
In this article, we have seen how we can make use of AWS Lambda and Cloudfront to protect s3 buckets with Basic Auth Mechanism. If you are interested in cloud and just getting started, then feel free to check out other articles on our website. Please feel free to comment if you encounter any issues.
Further Reading
AWS CloudFront documentation
How to use CloudFront with S3 [Practical Example]
Getting started with AWS Lambda [Tutorial]