Created
August 13, 2014 13:45
-
-
Save janez89/b60383593305fc10fd3a to your computer and use it in GitHub Desktop.
NodeJS basic authentication without framework.
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
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