Skip to content

Instantly share code, notes, and snippets.

@janez89
Created August 13, 2014 13:45
Show Gist options
  • Save janez89/b60383593305fc10fd3a to your computer and use it in GitHub Desktop.
Save janez89/b60383593305fc10fd3a to your computer and use it in GitHub Desktop.
NodeJS basic authentication without framework.
var http = require('http');
http.createServer(function (req, res) {
// get authorization data
var header=req.headers['authorization'] ||'',
token=header.split(/\s+/).pop()||'',
auth=new Buffer(token, 'base64').toString(),
parts=auth.split(/:/),
username=parts[0],
password=parts[1];
// check username and password
if (username != 'admin' || password != 'admin') {
res.writeHead(401, {
'WWW-Authenticate': 'Basic realm="Admin"'
});
return res.end('401 Unauthorized');
}
// authorized
res.writeHead(200, { 'Content-Type': 'text/plain'});
res.end('Welcome Admin!');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment