How can I use the Management API in Actions?

Question: How can I use the Management API in Actions?

Answer:

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. You can use the api object to update user metadata in a pre-user-registration or post-login action:

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

If you need to use the Management API for something other than updating metadata, then you will need to create and authorize a machine-to-machine application 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).

Here are the 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:

You can find the domain, client ID, and client secret in the application settings of the app you 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.assignRolestoUser(params, data)
  } catch (e) {
    console.log(e)
    // Handle error
  }
};

Note: As mentioned in the Actions Limitations docs, calls made to the Auth0 Management API and User Metadata updates are rate limited.

If you have specific feedback about Actions, please consider submitting a feature request with the actions tag in our feedback category:

Supporting Documentation:

Documentation: Actions
Community Topic: Using the management API in flow actions

2 Likes