What is the best way to store roles and retrieve it? (Conditionaln rendering on frontend)

Hi all,

I have a web app where a lot of user roles exist and therefore I need to hide/show functionality based on their role. Now I don’t really understand from the document perspective, what the best way is, to get a users role and where to actually store it. As far as I understand, I need to call the management API always.
Can’t I somehow store it in the json i receive in the api/me call? (Thats the method for node.js auth0.handleProfile(req, res)

Hi @ibi!

One way to keep track of a user’s role would be to add their role to the ID Token or Access Token when they authenticate so that the frontend can decode the token and know the user’s role.

You can create a Rule to do this: Sample Use Cases: Rules with Authorization

Here are some other resources related to Role-Based Access Control (RBAC):

1 Like

Thanks Stephanie,

So this rule is called on every login, respectively every request where the user is authenticated?

Yes, Rules are JavaScript functions that execute within an isolated serverless Webtask container every time a user authenticates.

The Rules configured within your Auth0 tenant will run after authentication takes place and before the redirect back to your application.

Rules are passed a User Object and Context Object which allow them to do many things like add data to the user profile or throw an error if a user hasn’t verified their email address.

You can try adding the role to the ID Token and Access Token by creating a new Rule in the dashboard:

Paste the following into the new rule.

function (user, context, callback) {
  const namespace = 'http://yournamespace.com';
  const assignedRoles = (context.authorization || {}).roles;

  let idTokenClaims = context.idToken || {};
  let accessTokenClaims = context.accessToken || {};

  idTokenClaims[`${namespace}/roles`] = assignedRoles;
  accessTokenClaims[`${namespace}/roles`] = assignedRoles;

  context.idToken = idTokenClaims;
  context.accessToken = accessTokenClaims;

  callback(null, user, context);
}

To test it out, you’ll need to give your user a role and then log in and inspect the ID Token they are issued (example ID token)

Thanks a lot. I struggled with this until now.

1 Like

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