Wednesday, October 10, 2018

How do we add Digest Authentication to the http requests in Node JS?

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
    }
);

References:
https://www.haykranen.nl/2011/06/21/basic-http-authentication-in-node-js-using-the-request-module/

No comments:

Post a Comment