Adding user roles to access token

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