Using the Management API in Actions
This article provides steps for calling the Management API in Actions.
- Management API
- Actions
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:
- Create a Machine-to-Machine Application to represent the custom Action.
-
Authorize the Machine-to-Machine Application created in Step 1 to access the Management API, ensuring the required permission scopes are granted.
-
Navigate to the settings page for the Machine-to-Machine Application and locate its
domain,client ID, andclient secret. -
Securely store the
domain,client ID, andclient secretretrieved in Step 3 within the custom Action'sevent.secretsobject. -
Add the
auth0Node.js module as a dependency in the Action editor. -
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 apost-loginAction. 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:
- Calls to the Auth0 Management API and User Metadata updates made from within Actions are subject to rate limits. Minimize Management API usage within Actions to prevent exceeding these limits. For further details, refer to the documentation on Actions Limitations and Limiting Calls to the Management API.
- When updating user information via Actions, using a
post-loginAction is generally recommended over using apost-user-registrationAction. Refer to the relevant FAQ for additional context in Is it Possible to Use a Post-User Registration Action (or Hook) to Update a User.
Check out this video: