Skip to content

Instantly share code, notes, and snippets.

@takaheraw
Created January 4, 2013 10:18
Show Gist options
  • Save takaheraw/4451493 to your computer and use it in GitHub Desktop.
Save takaheraw/4451493 to your computer and use it in GitHub Desktop.
var http = require('http');
var host = '192.168.11.14';
var port = 1337;
var htpasswd = {'alice' : 'alicepass'};
var server = http.createServer(function(req, res){
function showAuthContent(res, username, password){
if(username in htpasswd && htpasswd[username] === password){
res.writeHead(200, {'Content-Type' : 'text/plain' });
res.end('Hello Authed World\n');
}else{
res.writeHead(403, {'Content-Type': 'text/plain'});
res.end('Forbidden\n');
}
}
if(req.headers.authorization){
var header = req.headers.authorization.split(' ');
if(header[0] === 'Basic' && header[1]){
var data = (new Buffer(header[1], 'base64').toString()).split(':');
showAuthContent(res, data[0], data[1]);
}else{
res.writeHead(403, {'Content-Type': 'text/plain'});
res.end('Forbidden\n');
}
}else{
res.writeHead(401, {'Content-Type': 'text/plain',
'WWW-Authenticat' : 'Basic realm="Username"'});
res.end('Authorization Required');
}
});
server.on('error', function(e){
console.log('Server Error: ', e.message);
});
server.listen(port, function(){
console.log('listening on', host + ':' + port);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment