Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Example of HTTP Basic Auth in NodeJS
var http = require('http');
var server = http.createServer(function(req, res) {
// console.log(req); // debug dump the request
// If they pass in a basic auth credential it'll be in a header called "Authorization" (note NodeJS lowercases the names of headers in its request object)
var auth = req.headers['authorization']; // auth is in base64(username:password) so we need to decode the base64
console.log("Authorization Header is: ", auth);
if(!auth) { // No Authorization header was passed in so it's the first time the browser hit us
// Sending a 401 will require authentication, we need to send the 'WWW-Authenticate' to tell them the sort of authentication to use
// Basic auth is quite literally the easiest and least secure, it simply gives back base64( username + ":" + password ) from the browser
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="Secure Area"');
res.end('<html><body>Need some creds son</body></html>');
else if(auth) { // The Authorization was passed in so now we validate it
var tmp = auth.split(' '); // Split on a space, the original auth looks like "Basic Y2hhcmxlczoxMjM0NQ==" and we need the 2nd part
var buf = new Buffer(tmp[1], 'base64'); // create a buffer and tell it the data coming in is base64
var plain_auth = buf.toString(); // read it back out as a string
console.log("Decoded Authorization ", plain_auth);
// At this point plain_auth = "username:password"
var creds = plain_auth.split(':'); // split on a ':'
var username = creds[0];
var password = creds[1];
if((username == 'hack') && (password == 'thegibson')) { // Is the username/password correct?
res.statusCode = 200; // OK
res.end('<html><body>Congratulations you just hax0rd teh Gibson!</body></html>');
else {
res.statusCode = 401; // Force them to retry authentication
res.setHeader('WWW-Authenticate', 'Basic realm="Secure Area"');
// res.statusCode = 403; // or alternatively just reject them altogether with a 403 Forbidden
res.end('<html><body>You shall not pass</body></html>');
server.listen(5000, function() { console.log("Server Listening on http://localhost:5000/"); });
Copy link

Thank you, you have clarified most of my dubts :)

Copy link

If I want to use this to log into a specific "", where would I put the url in the code?

Copy link

jlopex commented Feb 26, 2014

@charlesdaniel, thanks for this piece of code, it does exactly what I needed :-)

Copy link

Awesome! Thanks for this!! Easy! Mine is setup to run over SSL, but with this simple example, I can easily tie it into auth tables in DB. Thanks!

Copy link

@thesailored wrote:

If I want to use this to log into a specific "", where would I put the url in the code?

Assume you mean and you only want to accept incoming connections on port 8080 for the hostname If so, you'd just modify line 53:

server.listen(port, [hostname], [backlog], [callback])

So ...

server.listen(8080, '')

See docs on server.listen.

Copy link

Copy link

cosu commented Jun 18, 2016

If the password has a colon plain_auth.split(':'); will return an array with size >2 and the extracted password will be incomplete.

Copy link

cosu is right.
You should use following syntax.

Copy link

mauroao commented Jul 26, 2017

Thank you !

Copy link

fusion27 commented Aug 28, 2017

Massively appreciate the post @charlesdaniel, thanks so much for taking the time and spreading the good word!

Copy link

Very useful, thanks

Copy link

Thanks a lot man. This short and straight to the point piece of code really helped me understand it.

Copy link

wo, very simple but good explain example :)

Copy link

Thank you for explaining in detail each step and why each piece of code is needed. I wish there were more examples of code on the web explained this clearly.

Copy link

ya this is to much helpfull!!

Copy link

Still useful in 2021!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment