Running a rule to call an API does not work due to 401 error

I have written a rule that posts a new user to my API. The rule fires when I sign up a new user. My API refuses the POST with a 401 error.

When I debug the rule, the context.accessToken is empty {}. How do I get an access token to pass to my API? I can’t make heads or tails of the rule documentation.

  function (user, context, callback) {
   if (context.stats.loginsCount === 1) {
    return callback(null, user, context);
  }
  const request = require('request');
  
  const payload = _.extend({}, user, context);

  request.post({
    url: configuration.MY_NEW_USER_API,
    json: payload,
    headers: {
      "Authorization": "Bearer " + context.accessToken
    }
  });
  callback(null, user, context);
}

Thanks!
David

The context.accessToken available in rules is a way for a rule to influence the claims/scope of an access token that will be issued as part of the authentication transaction for which the rules are running. In other words, it DOES NOT contain an actual access token.

In your situation, the final implementation will depend on the API that you’re calling. In particular, is the API being called by rules an API you defined in the Auth0 tenant itself? If yes, then access tokens issued for that API are issued by your Auth0 tenant itself and one possibility would be to treat rules as a machine to machine application and obtain an access token for the API through a client credentials grant (Client Credentials Flow). However, since rules won’t easily allow you to cache the access token this would have significant considerations and costs.

Hey there!

As this topic is related to Rules - Hooks - Actions and Rules & Hooks are being deprecated soon I’m excited to let you know about our next Ask me Anything session in the Forum on Thursday, January 18 with the Rules, Hooks and Actions team on Rules & Hooks and why Actions matter! Submit your questions in the thread above and our esteemed product experts will provide written answers on January 18. Find out more about Rules & Hooks and why Actions matter! Can’t wait to see you there!

Learn more here!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.