Skip to content

Instantly share code, notes, and snippets.

@MCheli
Created June 27, 2016 21:02
Show Gist options
  • Save MCheli/aa308ecd1fde920e6453e6d0a3a0a703 to your computer and use it in GitHub Desktop.
Save MCheli/aa308ecd1fde920e6453e6d0a3a0a703 to your computer and use it in GitHub Desktop.
Basic Authentication Express + Node Server
var express = require('express');
var morgan = require('morgan');
var hostname = 'localhost';
var port = 3000;
var app = express();
app.use(morgan('dev'));
function auth (req, res, next){
console.log(req.headers);
var authHeader = req.headers.authorization;
if(!authHeader) {
var err = new Error('You are not authenticated!');
err.status = 401;
next(err);
return;
}
var auth = new Buffer(authHeader.split(' ')[1], 'base64').toString().split(':');
var user = auth[0];
var pass = auth[1];
if (user == 'admin' && pass == 'password') {
next();
} else {
var err = new Error('You are not authenticated!');
err.status = 401;
next(err);
}
}
app.use(auth);
app.use(express.static(__dirname + '/public'));
app.use(function(err,req,res,next) {
res.writeHead(err.status || 500, {
'WWW-Authenticate': 'Basic',
'Content-Type': 'text/plain'
});
res.end(err.message);
});
app.listen(port, hostname, function(){
//noinspection JSAnnotator
console.log(`Server running at http://${hostname}:${port}/`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment