Using the Management API in Actions

Last Updated: Oct 28, 2024

Overview

This article details how to call the Management API in Actions.

Applies To

  • Management API
  • Actions

Solution

Please see the below video.

There are plans to expand functionality in Actions even more in the future. Currently, the only built-in method for using the Management API from within Actions is for updating user metadata. Use the api object to update user metadata in a pre-user-registration 27 or post-login action 50:

  • api.user.setUserMetadata(name, value)
  • api.user.setAppMetadata(name, value)

If using the Management API for something other than updating metadata, create and authorize a machine-to-machine application 54 for the Action (see steps below).

NOTE: For making updates to the user, it’s recommended not to use a post-user-registration action. Instead, consider using a post-login action (FAQ 63).

Steps for using the Management API in a custom Action:

  1. Create a Machine-Machine Application for the Action:
    rtaImage (23).jpeg
  2. Authorize it to use the Management API with the required scopes:
    rtaImage (24).jpeg
  3. Store the application’s credentials in the Action’s event.secrets object:
    Find the domain, client ID, and client secret in the application settings of the app created in step 1.
    rtaImage (25).jpeg
  4. Add the auth0 npm module:
    rtaImage (26).jpeg
  5. Initialize and use the Management API in the Action:
    This post-login Action example adds a default role to the user when they first log in.
exports.onExecutePostLogin = async (event, api) => {
  if (event.stats.logins_count !== 1) {
    return;
  }

  const ManagementClient = require('auth0').ManagementClient;

  const management = new ManagementClient({
      domain: event.secrets.domain,
      clientId: event.secrets.clientId,
      clientSecret: event.secrets.clientSecret,
  });

  const params =  { id : event.user.user_id};
  const data = { "roles" : ["ROLE_ID"]};

  try {
    const res = await management.users.assignRoles(params, data)
  } catch (e) {
    console.log(e)
    // Handle error
  }
};

Related References

9 Likes