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

  1. As mentioned in the Actions Limitations docs, calls made to the Auth0 Management API and User Metadata updates are rate limited, so please limit the usage of management API in actions to as minimum as possible. See Limit calls to the Management API.
  2. 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).

Steps for using the Management API in a custom Action:

  1. Create a Machine-Machine Application for the Action:
  2. Authorize it to use the Management API with the required scopes:
  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.
  4. Add the auth0 npm module:
  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