Skip to content

Instantly share code, notes, and snippets.

@joecritch
Created December 14, 2011 12:30
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save joecritch/1476393 to your computer and use it in GitHub Desktop.
Save joecritch/1476393 to your computer and use it in GitHub Desktop.
Basic auth middleware for Node.js Express
function basic_auth (req, res, next) {
if (req.headers.authorization && req.headers.authorization.search('Basic ') === 0) {
// fetch login and password
if (new Buffer(req.headers.authorization.split(' ')[1], 'base64').toString() == 'usernamehere123:passwordhere123') {
next();
return;
}
}
console.log('Unable to authenticate user');
console.log(req.headers.authorization);
res.header('WWW-Authenticate', 'Basic realm="Admin Area"');
if (req.headers.authorization) {
setTimeout(function () {
res.send('Authentication required', 401);
}, 5000);
} else {
res.send('Authentication required', 401);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment