Auth0 Home Blog Docs

How can I retrieve a user's roles using react-auth0-spa?

I’m using the react-auth-spa from here: https://github.com/auth0-samples/auth0-react-samples/blob/master/01-Login/src/react-auth0-spa.js. I have created an admin role for my users. How can I view what roles a user has so that I can restrict which routes they’re allowed to access?

I’m using roles created from the location in the following screenshot:

Hi @groffcole,

Welcome to the Auth0 Community Forum!

I would recommend adding the roles to an id token via a rule.

Let me know if that doc helps.

Thanks,
Dan!

1 Like

@dan.woda - This is very helpful, thank you! I added the exact rule from the link you provided and I’m able to see the roles in the id token and the access token returns from the spa sdk.

One thing I’m curious about is this from the rule:

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

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

Does this just add the assigned roles to both the id token and the access token with a key of ${namespace}/roles? Is this specific key name significant or can it be whatever I want?

Also, why do the variables include the work Claims? Why not just call them idToken and accessToken?

Would you add the roles to the access token as well because this allows the back-end to authorized?

Thanks again!

Is this specific key name significant or can it be whatever I want?

It can be whatever you like. Just need to be proper namespace syntax.

Also, why do the variables include the work Claims ? Why not just call them idToken and accessToken ?

You can name it whatever you like, incl. just idToken, which also makes perfect sense. Above was just an example. I would actually also name it as per your suggestion.

Would you add the roles to the access token as well because this allows the back-end to authorized?

If you need roles in the backend, then: yes. If you need to know the roles in the frontend, then the ID token is relevant.

2 Likes

@groffcole,

In addition to the things @mathiasconradt said, take a look at the doc for custom claims:

1 Like

This is great. Thank you both. When I get the chance, I will try this out on my front-end.

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