Skip to content

Instantly share code, notes, and snippets.

@MarcoAlejandro
Created December 26, 2018 11:19
Show Gist options
  • Save MarcoAlejandro/5ca42e1db7359b7ba6dc60c8ea273b90 to your computer and use it in GitHub Desktop.
Save MarcoAlejandro/5ca42e1db7359b7ba6dc60c8ea273b90 to your computer and use it in GitHub Desktop.
Authentication recipe in expressjs
//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