How to Add password protection to your static website on AWS S3 using AWS Lambda and Cloudfront

2 min. read

In this guide, we will show you how to protect your static website, hosted on AWS S3, with Basic Authentication

Introduction

This article assumes that you already have:

  • AWS S3 Bucket setup
  • AWS Cloudfront Distribution
  • Linked a Domain to Cloudfront

Create a Lambda Edge Function

  • Open AWS Console

  • Navigate to Lambda

  • Make sure you are in the N. Virginia region

  • Click “Create function”

  • A new screen will appear, named “Create function”:

  • Give the function a name, for this article, “lambda-basic-auth”

  • Select NodeJS Runtime

  • Click “Create”

  • You should now see the newly created function:

  • In the code section, you should see the following javascript code:

Index.js Sample
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
exports.handler = async (event) => {

const req = event.Records[0].cf.request;

if(req && req.headers && req.headers.authorization ){
const basicAuthHeader = req.headers.authorization[0].value;
const basicAuthString = `Basic ${new Buffer('admin' + ":" + 'password').toString('base64')}`;

if(basicAuthHeader === basicAuthString){
return req;
}
}

const res = {
status: 401,
body: "Unauthorized",
headers:{
'www-authenticate':[
{
key: 'WWW-Authenticate',
value: 'Basic'
}
]
}
}

return res
};



In Trust relationship, click “Edit trust policy”, and replace with the following:

Trust Policy
1
2
3
4
5
6
7
8
9
10
11
12
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": ["lambda.amazonaws.com", "edgelambda.amazonaws.com"]
},
"Action": "sts:AssumeRole"
}
]
}
  • Click deploy, and then Actions - Deploy new Version
  • Go to the AWS Cloudfront Console
  • Select the Distribution you want to edit.
  • Select “Behaviors”
  • Scroll down to the section “Function associations”
  • Next to the “Viewer request” label, select Lambda@Edge, and fill in the ARN from the section above.
  • Wait for the distribution to deploy

References

Videos