Basic HTTP authentication in Node.js using the request module

/ Filed under english, ict+web, tutorial / howto / 3 comments

Here’s an easy way to use basic authentication while using the request library for Node.js.

Unfortunately request doesn’t come with an easy convenience parameter you can use, so you need to provide it by yourself. The common way is to add it as an extra HTTP header.

Let’s say you need to login to example.com using user and pass as your username/password.

    
var request = require('request'),
    username = "john",
    password = "1234",
    url = "http://www.example.com",
    auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

request(
    {
        url : url,
        headers : {
            "Authorization" : auth
        }
    },
    function (error, response, body) {
        // Do more stuff with 'body' here
    }
);

This is pretty verbose. Fortunately, you can use a trick using the URL itself, as specified in RFC 1738. Simply pass the user/pass before the host with an @ sign.

var request = require('request'),
    username = "john",
    password = "1234",
    url = "http://" + username + ":" + password + "@www.example.com";

request(
    {
        url : url
    },
    function (error, response, body) {
        // Do more stuff with 'body' here
    }
);

Nice one huh?

Add a comment

3 comments

  • Anonymous

    Awesome, thanks for posting this. Not sure why this isn’t highlighted in the readme file for the request module

  • Reto

    Nice but deprecated according to rfc3986 :(

  • Ravi Agrawal

    Excellent work