Skip to content

Instantly share code, notes, and snippets.

@jongha
Created May 15, 2019 09:50
Show Gist options
  • Save jongha/aff75ed8df6a8d03cb366097d0a86d43 to your computer and use it in GitHub Desktop.
Save jongha/aff75ed8df6a8d03cb366097d0a86d43 to your computer and use it in GitHub Desktop.
HTTP basic auth for Node.js
app.use((req, res, next) => {
const auth = { login: 'username', password: 'password' };
const b64auth = (req.headers.authorization || '').split(' ')[1] || '';
const [login, password] = new Buffer(b64auth, 'base64').toString().split(':');
if (login && password && login === auth.login && password === auth.password) {
return next();
}
res.set('WWW-Authenticate', 'Basic realm="401"');
res.status(401).send('Authentication required.');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment