Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.