Skip to content

Instantly share code, notes, and snippets.

@mminer
Created December 12, 2018 21:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mminer/6670767263240f8ac39b539112629f45 to your computer and use it in GitHub Desktop.
Save mminer/6670767263240f8ac39b539112629f45 to your computer and use it in GitHub Desktop.
Express middleware for HTTP Basic Authentication.
function basicAuthMiddleware(request, response, next) {
const { authorization = '' } = request.headers;
const [, credentials] = authorization.split(' ');
const decoded = new Buffer(credentials || '', 'base64').toString();
const splitIndex = decoded.indexOf(':');
const username = decoded.substring(0, splitIndex);
const password = decoded.substring(splitIndex + 1);
// TODO: supply valid values for username and password
if (username !== USERNAME || password !== PASSWORD) {
response.set('WWW-Authenticate', 'Basic realm="Secure site"');
response.sendStatus(401);
return;
}
next();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment