Recently I’ve played a lot with Node and Express in web development, it’s simple and has everything we need to be able to develop, has module for basically everything and you can see that the community is growing every day: http://www.modulecounts.com.

But sometimes we need to protect the apps with a simple authentication (user/password) just to be able to demonstrate to clients, it’s necessary in many cases.

Recently I had an experience using http-auth and surprised me by the ease and speed of configuration, it has integration with various frameworks such as Express, Koa, Hapi, etc, below I demonstrate how to set up with Express.

First, you need to install it:

npm install http-auth

Now I show you my script (app.js) with the Express/Node code and then the code using http-auth.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
'use strict';

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

app.use(express.static('www'));

app.get('*', function (req, res) {
  res.render('index.html.ejs');
});

app.listen(4000, function() {
  console.log('Node app is running');
});

And now with http-auth:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
'use strict';

var express = require('express');
var app = express();
var auth = require('http-auth');

var basic = auth.basic({
  realm: 'Secret'
}, function(username, password, callback) {
  callback(username == 'username' && password == 'password');
});

app.use(auth.connect(basic));
app.use(express.static('www'));

app.listen(4000, function() {
  console.log('Node app is running');
});

Pretty simply, there are 3 steps you need to do:

  1. Save a reference of htto-auth in a variable
1
var auth = require('http-auth');
  1. Setup the auth module following the doc:
1
2
3
4
5
var basic = auth.basic({
  realm: 'Secret'
}, function(username, password, callback) {
  callback(username == 'username' && password == 'password');
});
  1. Setup Middleware:
1
app.use(auth.connect(basic));

Comments