Auth0 Home Blog Docs

Invoke and consuming a rest call

#1

I am looking for way to to invoke a REST call against our proprietary server.

I need a way to add custom headers to the request and consume the json response.

This call will ideally be done on login , based on the users email address custom lookup is done on the application server and we then add addtional attributes to the user profile.

I need an example showing me how I can invoke a HTTP call and consume its response.

Thank You

#2

Not sure what would be Auth0’s involvement in the example you are looking for. Are you looking for a REST API call sample from within a rule? If so, you can use the request library like this:

var rule = function(user, context, callback) {
  // from https://github.com/request/request#custom-http-headers
  const request = require("request");

  const options = {
    url: "https://api.github.com/repos/request/request",
    headers: {
      "User-Agent": "request"
    },
    json: true,
    
  };

  function callback(error, response, body) {
    if (!error && response.statusCode == 200) {
      const info = JSON.parse(body);
      console.log(info.stargazers_count + " Stars");
      console.log(info.forks_count + " Forks");
    }
  }
};
#3

Is there a link for request library docs, how do I invoke the post/get call on the request object that we have defined.

I tried to use your sample directly in an empty rule it complained callback is defined twice.

#4

Try this: https://www.npmjs.com/package/request

#5

Hello Nicolas,
I was able to successfully invoke my REST call and process the json reponse, my next step was to add addtional claims to the idToken, below if the code snippet

var status = ‘DENIED’;
request(options, function (error, response, body) {
if (!error && response.statusCode === 200) {
var info = JSON.parse(body);
if(info.length > 0) {
status = info[0].value;
console.log(status);
}
} else{
console.log(response.statusCode);
console.log(response.error);
}
});

console.log(‘After request returns :’ + status);

if(status === ‘APPROVED’){
console.log('Set id token to approved ');
context.idToken[‘https://example.com/grp’] = [‘Student’,‘Approved Student’];
} else {
context.idToken[‘https://example.com/grp’] = [‘Student’];
}

Even if I have status as APPROVED from the rest call it always stays as DENIED. How do I alter the context object from within the request.

#6

I want to return the response body of the request call to further set the context object.

I have tried several ways to accomplish this but to no success so far, any ideas will be appreciated.