Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP Client based on NodeJS: How to authenticate a request?

This is the code I have to make a simple GET request:

var options = {     host: 'localhost',     port: 8000,     path: '/restricted' };  request = http.get(options, function(res){     var body = "";     res.on('data', function(data) {         body += data;     });     res.on('end', function() {         console.log(body);     })     res.on('error', function(e) {         console.log("Got error: " + e.message);     }); }); 

But that path "/restricted" requires a simple basic HTTP authentication. How do I add the credentials to authenticate? I couldn't find anything related to basic http authentication in NodeJS' manual. Thanks in advance.

like image 592
João Pinto Jerónimo Avatar asked Aug 02 '11 20:08

João Pinto Jerónimo


People also ask

How do I authenticate an HTTP client?

You can set the required credentials to the CredentialsProvider object using the setCredentials() method. AuthScope object − Authentication scope specifying the details like hostname, port number, and authentication scheme name. Credentials object − Specifying the credentials (username, password).

How do I authenticate HTTP GET request?

You can query the credentials of the current user by using the HTTP GET method on the login resource, providing the basic authentication information to authenticate the request. This request returns information about the user name, and the roles that the user is assigned. For more information, see GET /login .


1 Answers

You need to add the Authorization to the options like a header encoded with base64. Like:

var options = {     host: 'localhost',     port: 8000,     path: '/restricted',     headers: {      'Authorization': 'Basic ' + new Buffer(uname + ':' + pword).toString('base64')    }          }; 
like image 144
Marcus Granström Avatar answered Sep 20 '22 00:09

Marcus Granström