0

For a web application I'm trying to pull some data from a RESTful service which requires basic authentication.

So far I've got the following code:

var req = request({
    auth: 'Basic aGVsbG8gd29ybGQ=', //base64 encoded credentials "hello world"
    url: url.resolve("https://rest.someurl.com", "/url/to/data.xml"),
    method: "GET",
    jar: true
}, function(err, res, body) {

  if(err) return util.err(err);

  console.log(body);

});

When I pull this URL through Postman service with the authentication header set it returns the data properly. Also when I remove the auth option and enter the username/password in the URL directly I also get the data back as normal. The only situation I don't get any data back is with my code above.

What's wrong with my code above or what should I add to it to make it work?

2 Answers 2

1

Try letting request handle the basic authorization header by just providing the cleartext username and password in the URL. request will format it for you. You also most likely don't need the jar option and the default method is GET so no need to specify that.

var username = "your-username";
var password = "your-password";
var req = request({
    url: "https://" username + ":" + password + "@rest.someurl.com/url/to/data.xml")
}, function(err, res, body) {

  if(err) return util.err(err);

  console.log(body);

});
Sign up to request clarification or add additional context in comments.

2 Comments

I'd rather not put the username and password directly in the URL as it should be passed on via the header instead.
It won't be passed in the URL. Read up on how basic authentication works. request will take the credentials, base64 encode them as per the HTTP spec, and pass them in the "Authorization" header when making the request to the server. It is identical from a security perspective to your original code (except that it will actually work).
0

Sharing a slightly larger scope of my code I found that I needed to move the request() call to inside of the callback I have to get the username and password propagating correctly.

var getData = exports.getData = function() {

  var credentials = "";
  getCredentials(function(creds) {
    credentials = {
      'user': creds.username,
      'pass': creds.password
    }
    var req = request({
        auth: credentials,
        url: url.resolve("https://rest.someurl.com", "/url/to/data.xml")
    }, function(err, res, body) {

      if(err) return util.err(err);

      console.log(body);

    });
  });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.