-
-
Save cpilsworth/0012ad9675e0bd530877170142d98d54 to your computer and use it in GitHub Desktop.
Basic HTTP Authentication for CloudFront with Lambda@Edge without credentials in code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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