Created
December 26, 2018 11:19
-
-
Save MarcoAlejandro/5ca42e1db7359b7ba6dc60c8ea273b90 to your computer and use it in GitHub Desktop.
Authentication recipe in expressjs
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
//authentication middleware. | |
function auth(req, res, next) { | |
console.log(req.headers); | |
var authHeader = req.headers.authorization; | |
if(!authHeader) { | |
var err = new Error('You are not authenticated'); | |
res.setHeader("WWW-Authenticate", 'Basic'); | |
err.status = 401; | |
next(err); | |
} | |
var auth = new Buffer(authHeader.split(' ')[1], 'base64').toString().split(':'); | |
var username = auth[0]; | |
var password = auth[1]; | |
if(username === 'admin' && password === 'password') { | |
next(); | |
} | |
else { | |
var err = new Error('Incorrect username/password'); | |
res.setHeader("WWW-Authenticate", 'Basic'); | |
err.status = 401; | |
next(err); | |
} | |
}; | |
app.use(auth); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment