Using the Management API in Actions

Last Updated: Dec 20, 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 two methods for interacting with the Management API from within Actions, depending on the goal:

Method 1: Updating User Metadata (Built-in):

To update user metadata within a pre-user-registration or post-login Action trigger, use the built-in api object with the appropriate method:

  • To set user metadata:
api.user.setUserMetadata(name, value)
  • To set application metadata:
api.user.setAppMetadata(name, value)

Method 2: Other Management API Operations (Machine-to-Machine Application)

If using the Management API for operations other than updating user metadata, follow this step explained in Create Machine-to-Machine Applications for Testing

Using the Management API in a Custom Action:

  1. Create a Machine-Machine Application for the Action:
  2. Authorize the Machine-to-Machine Application created in Step 1 to access the Management API, ensuring the required permission scopes are granted.
  3. Navigate to the settings page for the Machine-to-Machine Application and locate its domain, client ID, and client secret.
    1. Securely store the domain, client ID, and client secret retrieved in Step 3 within the custom Action’s event.secrets object.
    1. Add the auth0 Node.js module as a dependency in the Action editor.
    1. Initialize the Management API client within the Action script, using the application credentials stored in event.secrets.
      • Use the initialized Management API client object to perform the desired API operations within the Action script logic.
      • Example: A common use case is assigning a default role to a user upon their first login within a post-login Action. The code snippet below illustrates initializing the client and calling the relevant Management API endpoint:
        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
  }
};

NOTE:

9 Likes