Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useAuth0().user doesn't show the user Roles

Tags:

reactjs

jwt

auth0


I am having issues to get a Auth0 user Roles when I call the `useAuth0().user` react hook.

At the moment I am getting this:

    email: "[email protected]"
    email_verified: true
    name: "BB"
    nickname: "BB"
    picture: "https://..."
    sub: "auth0|ABC123"
    updated_at: "2021-02-17T17:24:17.989Z"

In the Auth0 dashboard, I have my user setup with an 'Admin' role and I am trying to set 'Rules' in order to pass the 'app_metadata' to the API response. I have seen a bunch of scripts to get the Rules, but none of them works.

context.authorization.roles, tested in the Auth0 create Rules test script window, always returns undefined. I am wondering if I am entering the namespace attached to the tokenID incorrectly. At the moment is the URL of the dev page I am using to access to login page. Is that correct? (https://dev-fkjer8938 etc....).

In theory I should be able to see:

"app_metadata": {
    "roles": [
        "admin"
    ]
},

Your help is much appreciated. Joe

like image 990
Joe Avatar asked Sep 01 '25 03:09

Joe


1 Answers

I'm not sure this will be an exact answer, but some things for consideration which might help:

When you assign roles to a user, they'll show up on the tokens depending on how you explicitly add them. I'm not sure they will be accessible via the useAuth0().user as from the documentation it looks like that's more for user/profile metadata. You might instead need to use getAccessTokenSilently (also from the useAuth0 hook). My application doesn't use the hooks implementation, so I'm not able to dig into that part.

This is an example rule I just tested in my setup which let me read the context, authorization, and roles when logging in to my application. I tested using the "Real-time Webtask Logs" extension:

function (user, context, callback) {
  // This namespace can be whatever you want - it will be the 'key' that holds
  // an array of roles on the users token
  const namespace = 'http://anything.you.want';
  const assignedRoles = (context.authorization || {}).roles;
  
  console.log(context);
  console.log(context.authorization);
  console.log(assignedRoles);

  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);
}

Then in my application I was able to see the role I added on my users token:

{
  ...
  "http://anything.you.want/roles": [
    "Test-Role"
  ],
  "given_name": "Ben",
  "updated_at": "2021-02-17T21:20:02.782Z",
  "email_verified": true,
  "iat": 1613596822,
  "exp": 1613632822,
  ...
}
like image 108
Ben Avatar answered Sep 03 '25 14:09

Ben