Adding user roles to access token

Following this guide (Login Flow), I can successfully add the list of users roles to the access token, but it only works when the role has been assigned as part of organization.

If I assign the role to the user directly (from the user details page), it does not show up in the list of roles.

Is it possible to include user roles that have been added directly?

Hey there @chris.tice welcome to the community!

This is a bit of a tricky use case - The following topic is more geared towards permissions, the same goes for roles as well:

Hope this helps!

What I ended up doing is using a custom Action with the Management API to query for a users direct roles, and adding the list of roles to the token as a custom claim.

exports.onExecutePostLogin = async (event, api) => {
  const ManagementClient = require('auth0').ManagementClient;
  const management = new ManagementClient({
      domain: event.secrets.domain,
      clientId: event.secrets.clientId,
      clientSecret: event.secrets.clientSecret,
  });

  const namespace = 'my-namespace';
  try {
    // Get the list of global roles for a user
    const roles = await management.getUserRoles({
      id: event.user.user_id,
    });

    const roleNames = roles.map((role) => role.name);

    api.idToken.setCustomClaim(`${namespace}/globalRoles`, roleNames);
    api.accessToken.setCustomClaim(`${namespace}/globalRoles`, roleNames);
  } catch (e) {
    console.log(e);
  }
};
2 Likes

Hey @chris.tice thanks for sharing here :smile:

Just be aware that calls to the Management API are rate limited as stated in the doc on Actions limitations.

You may also want to look into caching Management API tokens:

Cheers!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.