Basic HTTP authentication in Node.JS?

I use this code for my own starter sites with auth.

It does several things:

  • basic auth
  • return index.html for / route
  • serve content without crashing and silent handle the error
  • allow port parameter when running
  • minimal amount of logging

Before using the code, npm install express

var express = require("express");
var app = express();

//User validation
var auth = express.basicAuth(function(user, pass) {     
     return (user == "username" && pass == "password") ? true : false;
},'dev area');

/* serves main page */
app.get("/", auth, function(req, res) {
try{
    res.sendfile('index.html')
}catch(e){}
});

/* add your other paths here */

/* serves all the static files */
app.get(/^(.+)$/, auth, function(req, res){ 
try{
    console.log('static file request : ' + req.params);
    res.sendfile( __dirname + req.params[0]); 
}catch(e){}
});

var port = process.env.PORT || 8080;
app.listen(port, function() {
    console.log("Listening on " + port);
});

The username:password is contained in the Authorization header as a base64-encoded string.

Try this:

const http = require('http');
 
http.createServer(function (req, res) {
  var header = req.headers.authorization || '';       // get the auth header
  var token = header.split(/\s+/).pop() || '';        // and the encoded auth token
  var auth = Buffer.from(token, 'base64').toString(); // convert from base64
  var parts = auth.split(/:/);                        // split on colon
  var username = parts.shift();                       // username is first
  var password = parts.join(':');                     // everything else is the password
 
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('username is "' + username + '" and password is "' + password + '"');
}).listen(1337, '127.0.0.1');

From HTTP Authentication: Basic and Digest Access Authentication - Part 2 Basic Authentication Scheme (Pages 4-5)

Basic Authentication in Backus-Naur Form

basic-credentials = base64-user-pass
base64-user-pass  = <base64 [4] encoding of user-pass,
                    except not limited to 76 char/line>
user-pass   = userid ":" password
userid      = *<TEXT excluding ":">
password    = *TEXT

If you're using express, you can use the connect plugin (included with express):

//Load express
var express = require('express');

//User validation
var auth = express.basicAuth(function(user, pass) {     
   return (user == "super" && pass == "secret");
},'Super duper secret area');

//Password protected area
app.get('/admin', auth, routes.admin);

You can use node-http-digest for basic auth or everyauth, if adding authorization from external services are in you roadmap.