Skip to content

Instantly share code, notes, and snippets.

@cpilsworth
Forked from lmakarov/lambda-basic-auth.js
Last active May 22, 2019 23:42
Show Gist options
  • Save cpilsworth/0012ad9675e0bd530877170142d98d54 to your computer and use it in GitHub Desktop.
Save cpilsworth/0012ad9675e0bd530877170142d98d54 to your computer and use it in GitHub Desktop.
Basic HTTP Authentication for CloudFront with Lambda@Edge without credentials in code
'use strict';
var crypto = require('crypto');
// Lambda@Edge does not allow for environment variables so compare credential hash rather than store credentials in code
// sha256 hex digest of the Basic base64(username:password) header
// e.g. show below, generated on mac:
// echo -n "Basic `(echo -n 'admin:password' | openssl base64)`" | shasum -a 256
const authStringSha256 = '9f19de0237c9bd59f803de1785f7aea4e3499b6929df3428e1b415fed81f797a';
function isAuthorized(header) {
var hash = crypto.createHash('sha256')
.update(header)
.digest('hex');
return hash === authStringSha256;
}
exports.handler = (event, context, callback) => {
// Get request and request headers
const request = event.Records[0].cf.request;
const headers = request.headers;
// Require Basic authentication
if (typeof headers.authorization == 'undefined' || !isAuthorized(headers.authorization[0].value)) {
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);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment