Skip to content

Instantly share code, notes, and snippets.

@tforster
Last active February 26, 2021 18:39
Show Gist options
  • Save tforster/a56719d7a0fbf2bdea4b7a18d09fd14b to your computer and use it in GitHub Desktop.
Save tforster/a56719d7a0fbf2bdea4b7a18d09fd14b to your computer and use it in GitHub Desktop.
Lambda@Edge function to implement basic auth

Basic Auth Lambda@Edge Function

Implements a simple basic auth function to attach to an AWS CloudFront distribution. Note that basic auth is inherently insecure and should not be used to protect content of value. It does work well to keep search engines and crawlers out of stage websites.

Usage

  1. Create a new Lambda function in us-east-1 (AWS does not support @Edge functions from other regions at this time.)
  2. Copy the contents of index.js to the new Lambda
  3. Replace {your-shared-username} and {your-shared-password} with actual values
  4. Attach to CloudFront as a viewer request function

Useful Information

One minor "gotcha" to be aware of is that @Edge Lambda functions require some additional permissions beyond typical AWS FaaS, namely lambda.amazonaws.com and edgelambda.amazonaws.com. Ensure the execution role has a trust policy that looks like this:

{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": ["lambda.amazonaws.com", "edgelambda.amazonaws.com"] }, "Action": "sts:AssumeRole" } ] }

"use strict";
exports.handler = async (event) => {
// Get request and request headers
const request = event.Records[0].cf.request;
const headers = request.headers;
// Set current shared credentials
const username = "{your-shared-username}";
const password = "{your-shared-password}";
// Construct the Basic Auth string
const authString = "Basic " + Buffer.from(username + ":" + password).toString("base64");
// Check to see if the credentials were NOT provided
if (typeof headers.authorization == "undefined" || headers.authorization[0].value != authString) {
console.log("401");
return {
status: "401",
statusDescription: "Unauthorized",
body: "Unauthorized",
headers: {
"www-authenticate": [{ key: "WWW-Authenticate", value: "Basic" }],
},
};
}
// Continue request processing
return request;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment