First, install the htpasswd module globally:
npm install -g htpasswdCreate a directory for your project and install http-auth module locally:
npm install http-authCreate a file auth-server.js with your editor of choice. Put the following lines into it:
var http = require("http");
var auth = require("http-auth");
var basic = auth.basic({
file: __dirname + '/htpasswd'
});
http.createServer(basic, function(req, res) {
console.log('Received request: ' + req.url);
res.end('User successfully authenticated: ' + req.user);
}).listen(8080);
Now create a file htpasswd in the same directory and populate it with a user name and a password separated by a colon:
forketyfork:mypasswordNow run the node server:
node auth-server.jsGo to the http://localhost:8080 URL in your browser. It will greet you with a standard basic-auth panel to enter your username and password. After successful authentication, you will see the message from server.
For more info on how to use the http-auth package for basic and digest authentication, see its page on github: https://github.com/gevorg/http-auth. For more info on htpasswd module, including using different types of hashes instead of plain text passwords, see https://github.com/gevorg/htpasswd.