How to Protect S3 bucket with Basic Authentication 


AWS

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.

How to Protect S3 bucket with Basic Authentication 

 

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

How to Protect S3 bucket with Basic Authentication 

 

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

NOTE:
Never have Public Access enabled if you are using S3 buckets for Sensitive Storage purposes. Have proper access controls so that no attacker can take advantage of the S3 bucket to upload or delete your files.

 

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>

How to Protect S3 bucket with Basic Authentication 

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.

How to Protect S3 bucket with Basic Authentication 

 

2. Choose the Origin Domain as the Amazon S3 bucket and create a new OAI identity and update the bucket policy.

How to Protect S3 bucket with Basic Authentication 

 

3. Enter the root document as index.html and leave all the other options default and click on Create

How to Protect S3 bucket with Basic Authentication 

 

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.

How to Protect S3 bucket with Basic Authentication 

 

Step 3 : Create a Lambda Function

1. Go to the Lambda dashboard using Search bar and click on Create Function

How to Protect S3 bucket with Basic Authentication 

 

2. Select the type as Blueprint and search for “cloudfront” , select cloudfront-response-generation from the search results and click on Configure

How to Protect S3 bucket with Basic Authentication 

 

3. On the following screen name your function and select the “Create the new role from AWS Policy templates”

How to Protect S3 bucket with Basic Authentication 

 

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.

How to Protect S3 bucket with Basic Authentication 

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);
};
NOTE:
Give your required username and password in authUser and authPass to protect s3 bucket.

 

2. After pasting the following code, click on Deploy which is just above it for the changes to be saved.

protect s3

 

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.

How to Protect S3 bucket with Basic Authentication 

 

4.Now create new Cloudfront trigger and leave the Cache behavior as * and Cloudfront event as Viewer request and click on Deploy.

How to Protect S3 bucket with Basic Authentication 

 

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.

How to Protect S3 bucket with Basic Authentication 

 

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]

 

Deepak Prasad

Deepak Prasad

He is the founder of GoLinuxCloud and brings over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive experience, he excels in various domains, from development to DevOps, Networking, and Security, ensuring robust and efficient solutions for diverse projects. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment