Applying Basic HTTP Authentication

Another common use for Express middleware is to apply basic HTTP authentication. HTTP authentication uses the Authorization header to send an encoded username and password from a browser to a server. If no authorization information is stored in the browser for the URL, the browser launches a basic login dialog box to allow the user to enter the username and password. Basic HTTP authentication works well for basic sites that require a minimal authenticate method and is very easy to implement.

The basic-auth-connect middleware function in Express provides the support to handle basic HTTP authentication. The basic-auth-connect middleware uses the following syntax:

var basicAuth = require('basic-auth-connect'),

express.basicAuth(function(user, pass){})

The function passed to basic-auth-connect accepts the username and password and then returns true if they are correct and false if they are not. For example:

app.use(express.basicAuth(function(user, password) {
  return (user === 'testuser' && pass === 'test'),
}));

Typically you store the username and password in the database and then, inside the authentication function, you retrieve the user object to validate against.

Listing 19.7 and Listing 19.8 illustrate how easy it is to implement the basic-auth-connect middleware. Listing 19.7 implements a global authentication. Listing 19.8 implements authentication against a single route. Figure 19.4 shows the browser requesting authentication and then the authenticated webpage.

Listing 19.7 express_auth.js: Implementing basic HTTP authentication globally for a site


01 var express = require('express'),
02 var basicAuth = require('basic-auth-connect'),
03 var app = express();
04 app.listen(80);
05 app.use(basicAuth(function(user, pass) {
06   return (user === 'testuser' && pass === 'test'),
07 }));
08 app.get('/', function(req, res) {
09   res.send('Successful Authentication!'),
10 });


Listing 19.8 express_auth_one.js: Implementing basic HTTP authentication for a single route


01 var express = require('express'),
02 var basicAuth = require('basic-auth-connect'),
03 var app = express();
04 var auth = basicAuth(function(user, pass) {
05   return (user === 'user1' && pass === 'test'),
06 });
07 app.get('/library', function(req, res) {
08   res.send('Welcome to the library.'),
09 });
10 app.get('/restricted', auth, function(req, res) {
11   res.send('Welcome to the restricted section.'),
12 });
13 app.listen(80);


Image

Figure 19.4 Using basic HTTP authentication.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.179.252