Last active
January 7, 2022 07:11
-
-
Save sheraz-haider/997b27a44b1233973dca57f7bda86d25 to your computer and use it in GitHub Desktop.
Basic HTTP Auth middleware for express
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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