What is the best way of retrieving user roles?

Hello!

I am building admin portal where I have to manage auth0 users. Today I ran into an exception (429 too many requests) with the rate limiter on that api “https://AUTH_DOMAIN/api/v2/users/USER_ID/roles”

Current flow of my backend for retrieving users with their roles:

  1. Get all users
  2. Retrieve role for each of the users (a request to “https://AUTH_DOMAIN/api/v2/users/USER_ID/roles” for each of the users to get his role)
  3. Return list of users to UI

Since I have more than 10 users already (and the limit for this endpoint is 10 requests) I started getting errors.

What is the best way to retrieve those roles without actually calling Management API for each user to get the role? Is there a way I can bind the user roles to the metadata with a rule for instance?

Any feedback will be appreciated.
Thanks,
Lyubomir

Hi @lyubomir.nikov

Thanks for getting in touch with us at Auth0 Community.

You can add the user roles to the app_metadata of a user account via a Post Login Action. The simplest implementation of this would be as below:

exports.onExecutePostLogin = async (event, api) => {
  var roles = event.authorization.roles;
  api.user.setAppMetadata("roles", roles);
};

You can read a bit more about this here https://auth0.com/docs/manage-users/user-accounts/metadata/manage-user-metadata

I hope this helps.
Warm regards.

Hello @SaqibHussain,

Thanks for your response!

As an admin for the application I would like to get the roles for each of the users registered for the application - therefore I am not interested in obtaining the role on login.

Regards

Hi @lyubomir.nikov

With this Action in place, when a user logs in, their roles will bind to the app_metadata on that user account which is what I think you were trying to achieve. So when you “Get all users” in your point 1, if the app_metadata is also being returned then the roles will also be returned and you won’t need to use “https://AUTH_DOMAIN/api/v2/users/USER_ID/roles”

Tradeoff here though is that you need to wait for all users to login at least once for the app_metadata to populate.

Warm regards.