rukĀ·si

šŸŸ¢ Express
šŸ†”Authentication

Updated at 2013-11-18 02:03

How to implement Basic authentication in Express.

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

// Synchronous
var auth1 = express.basicAuth('user', 'password');

// Synchronous function
var auth2 = express.basicAuth(function(user, pass) {
  return user === 'user' && pass === 'password';
});

// Asynchronous
var auth3 = express.basicAuth(function(user, pass, callback) {
    var result = (user === 'user' && pass === 'password');
    callback(null /* error */, result);
});

app.get('/', function(req, res) {
    res.send('Hello World - No Authentication');
});

app.get('/secret', auth3, function(req, res) {
    res.send('Hello World - Authentication');
});

app.listen(process.env.PORT || 8080);

Sources