Created
May 15, 2019 09:50
-
-
Save jongha/aff75ed8df6a8d03cb366097d0a86d43 to your computer and use it in GitHub Desktop.
HTTP basic auth for Node.js
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
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