Saturday, November 23, 2013

HTTP Basic Auth on Node.js

Implementing HTTP Basic Auth on node.js is a fairly simple exercise if you're using the express.js module.


On the server side, you utilize the built-in basicAuth() method in express.

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


app.use(express.basicAuth('username', 'password'));


On the client side, you pass the username/password in as an Authorization header.

Client Side
getValue = function(key, options)
{
    var retVal='';
    var opts = {
            host : 'theHost',
            port : '3000',
            path : '/rest/key'
            headers: {     'Content-Type' : 'text/plain',
                        'Authorization': 'Basic ' + new Buffer('username' + ':' + 'password').toString('base64') };
            method: 'GET'
    };
   
    var req = https.request(opts, function(res) {
        res.on('data', function(chunk) {
            retVal += chunk;
        });
        res.on('end', function() {
            if (options !== undefined && options.callback !== undefined)
                options.callback(retVal);
        });
    });
   
    req.on('error', function(err) {
       console.log('error');
    });
    req.end();
};

No comments:

Post a Comment