Skip to content

Instantly share code, notes, and snippets.

@sheraz-haider
Last active January 7, 2022 07:11
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 sheraz-haider/997b27a44b1233973dca57f7bda86d25 to your computer and use it in GitHub Desktop.
Save sheraz-haider/997b27a44b1233973dca57f7bda86d25 to your computer and use it in GitHub Desktop.
Basic HTTP Auth middleware for express
require('dotenv').config();
exports.basicAuth = function (req, res, next) {
// authentication middleware
const auth = { login: process.env.LOGIN, password: process.env.PASSWORD }; // change this
// parse login and password from headers
const b64auth = (req.headers.authorization || '').split(' ')[1] || '';
const [login, password] = Buffer.from(b64auth, 'base64')
.toString()
.split(':');
// Verify login and password are set and correct
if (login && password && login === auth.login && password === auth.password) {
// Access granted...
return next();
}
// Access denied...
res.set('WWW-Authenticate', 'Basic realm="401"'); // change this
res.status(401).send('Authentication required.'); // custom message
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment