124

As per title, how do I do that?

Here is my code:

var http = require('http');

// to access this url I need to put basic auth.
var client = http.createClient(80, 'www.example.com');

var request = client.request('GET', '/', {
    'host': 'www.example.com'
});
request.end();
request.on('response', function (response) {
  console.log('STATUS: ' + response.statusCode);
  console.log('HEADERS: ' + JSON.stringify(response.headers));
  response.setEncoding('utf8');
  response.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});
hong4rc
  • 3,999
  • 4
  • 21
  • 40
de_3
  • 3,389
  • 5
  • 20
  • 14

10 Answers10

308

You have to set the Authorization field in the header.

It contains the authentication type Basic in this case and the username:password combination which gets encoded in Base64:

var username = 'Test';
var password = '123';
var auth = 'Basic ' + Buffer.from(username + ':' + password).toString('base64');
// new Buffer() is deprecated from v6

// auth is: 'Basic VGVzdDoxMjM='

var header = {'Host': 'www.example.com', 'Authorization': auth};
var request = client.request('GET', '/', header);
Matt
  • 430
  • 6
  • 8
Ivo Wetzel
  • 46,459
  • 16
  • 98
  • 112
69

From Node.js http.request API Docs you could use something similar to

var http = require('http');

var request = http.request({'hostname': 'www.example.com',
                            'auth': 'user:password'
                           }, 
                           function (response) {
                             console.log('STATUS: ' + response.statusCode);
                             console.log('HEADERS: ' + JSON.stringify(response.headers));
                             response.setEncoding('utf8');
                             response.on('data', function (chunk) {
                               console.log('BODY: ' + chunk);
                             });
                           });
request.end();
Sujay
  • 2,198
  • 23
  • 32
20
var username = "Ali";
var password = "123";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
var request = require('request');
var url = "http://localhost:5647/contact/session/";

request.get( {
    url : url,
    headers : {
        "Authorization" : auth
    }
  }, function(error, response, body) {
      console.log('body : ', body);
  } );
Hamidreza Sadegh
  • 2,155
  • 31
  • 33
  • 1
    Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead – Sourabh Mar 22 '19 at 11:11
  • Buffer.from(options.auth.user + ":" + options.auth.password).toString('base64') – THE AMAZING Nov 21 '21 at 17:44
11

An easier solution is to use the user:pass@host format directly in the URL.

Using the request library:

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

I've written a little blogpost about this as well.

Husky
  • 5,757
  • 2
  • 46
  • 41
  • 21
    This is not ideal advice: any logging of URLs on either the client or server side could expose password values - this is a widely known security attack vector. I strongly recommend that no-one do this. Header values are better, and not using Basic authentication - in favor of Digest authentication or OAuth 1.0a (for example) is even better. This form of identification has also been deprecated in URIs in RFC 3986. – Les Hazlewood Jan 14 '14 at 04:38
  • Not using Basic Auth sounds like some bad advice. Basic auth requires transport security or it is completely insecure, yes. But basic auth with transport security is way more secure that Digest authentication. And OAuth 1 is a completely different beast with completely orthogonal security issues. – rich remer Jan 17 '17 at 20:54
  • @LesHazlewood It is not fair to say compromised clients can expose passwords. Compromised client simply means all bets are off. However, your deprecation warning is fair. – nurettin Sep 14 '18 at 11:59
9

for what it's worth I'm using node.js 0.6.7 on OSX and I couldn't get 'Authorization':auth to work with our proxy, it needed to be set to 'Proxy-Authorization':auth my test code is:

var http = require("http");
var auth = 'Basic ' + new Buffer("username:password").toString('base64');
var options = {
    host: 'proxyserver',
    port: 80,
    method:"GET",
    path: 'http://www.google.com',
    headers:{
        "Proxy-Authorization": auth,
        Host: "www.google.com"
    } 
};
http.get(options, function(res) {
    console.log(res);
    res.pipe(process.stdout);
});
vrtis
  • 712
  • 9
  • 9
  • 3
    For the edification of future readers: Thats because you are authenticating with your proxy server instead of authenticating with destination webserver (google). If you had needed to authenticate with the destination server then the Authorization header would be what you want to use. – Maks Jul 02 '13 at 04:50
  • Yes but often you need to do both so this is a solid answer – Mond Raymond Feb 24 '14 at 10:59
  • 1
    Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead – Sourabh Mar 22 '19 at 11:10
6
var http = require("http");
var url = "http://api.example.com/api/v1/?param1=1&param2=2";

var options = {
    host: "http://api.example.com",
    port: 80,
    method: "GET",
    path: url,//I don't know for some reason i have to use full url as a path
    auth: username + ':' + password
};

http.get(options, function(rs) {
    var result = "";
    rs.on('data', function(data) {
        result += data;
    });
    rs.on('end', function() {
        console.log(result);
    });
});
Manish Kumar
  • 538
  • 1
  • 7
  • 13
2

This code works in my case, after a lot of research. You will require to install the request npm package.

var url = "http://api.example.com/api/v1/?param1=1&param2=2";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
exports.checkApi = function (req, res) {
    // do the GET request
    request.get({
        url: url,
        headers: {
            "Authorization": auth
        }
    }, function (error, response, body) {
        if(error)
       { console.error("Error while communication with api and ERROR is :  " + error);
       res.send(error);
    }
        console.log('body : ', body);
        res.send(body);      

    });    
}
Xedret
  • 1,823
  • 18
  • 25
Nimish goel
  • 2,561
  • 6
  • 27
  • 42
  • 1
    Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead – Sourabh Mar 22 '19 at 11:11
2

I came across this recently. Which among Proxy-Authorization and Authorization headers to set depends on the server the client is talking to. If it is a Webserver, you need to set Authorization and if it a proxy, you have to set the Proxy-Authorization header

sdqali
  • 2,234
  • 1
  • 13
  • 6
0

For those not using DNS and needs more depth (you can also use request instead of get by simply replacing get with request like so: http.request({ ... })):

http.get({ 
    host: '127.0.0.1',
    port: 443,
    path: '/books?author=spongebob',
    auth: 'user:p@ssword#'
 }, resp => {
    let data;

    resp.on('data', chunk => {
        data += chunk;
    });

    resp.on('end', () => console.log(data));
}).on('error', err => console.log(err));
Miko Chu
  • 1,087
  • 14
  • 22
0

This is not well documented in Node.js, but you can use

require("http").get(
    {
      url: "www.example.com",
      username: "username",
      password: "mysecret",
    },
    (resp) => {
      let data;
      resp.on("data", (chunk) => (data += chunk));
      resp.on("end", () => console.log(data));
    }
  )
  .on("error", (err) => console.log(err));

Since the got pacakge inherits it's options object from http.request, username and password is also available there.

Pål Thingbø
  • 1,211
  • 1
  • 17
  • 17