Skip to content

Instantly share code, notes, and snippets.

@erhangundogan
Created December 5, 2017 13:43
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save erhangundogan/90b87669c15d5c67d2a5790fffa27788 to your computer and use it in GitHub Desktop.
Save erhangundogan/90b87669c15d5c67d2a5790fffa27788 to your computer and use it in GitHub Desktop.
AWS Lambda HTTP basic auth
'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 = 'user';
const authPass = 'pass';
// Construct the Basic Auth string
const authString = 'Basic ' + new Buffer(authUser + ':' + authPass).toString('base64');
// Require Basic authentication
if (headers.authorization && headers.authorization[0].value === authString) {
// Continue request processing if authentication passed
callback(null, request);
} else {
const body = 'Unauthorized';
const response = {
status: '401',
statusDescription: 'Unauthorized',
body: body,
headers: {
'www-authenticate': [{key: 'WWW-Authenticate', value:'Basic'}]
},
};
callback(null, response);
}
};
@tony-gutierrez
Copy link

Doesn't work without API Gateway, as the www-authenticate header will be remapped to a different name.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment