Using the Management API in Actions

Overview

This article provides steps for calling the Management API in Actions.

Applies To
  • Management API
  • Actions
Solution

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 the steps explained in Create Machine-to-Machine Applications for Testing.

 

 

Using the Management API in a Custom Action:

  1. Create a Machine-to-Machine Application to represent the custom Action.
    9142ec95ca3c84cb8fce559e7564ccdb6d3d285b_2_560x500.png
  2. Authorize the Machine-to-Machine Application created in Step 1 to access the Management API, ensuring the required permission scopes are granted.

    a06a75793b9035b32077ff7eb66eaa1ab36ab1db_2_647x500.png

  3. Navigate to the settings page for the Machine-to-Machine Application and locate its domain, client ID, and client secret.

  4. Securely store the domain, client ID, and client secret retrieved in Step 3 within the custom Action's event.secrets object.

    d5cc509c6297366b41a5cbead17695240d833eb1_2_690x387.png

  5. Add the auth0 Node.js module as a dependency in the Action editor.

    7923d0a2b256e6e8969a4a9501bd408d8b6992ee_2_690x325.png

  6. 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:
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:

 

Check out this video:

Recommended content

No recommended content found...