Ian Adem
Ian Adem

Reputation: 119

Get user_metadata Roles in Auth0

I am trying to get user Roles when after logged in in Auth0, as per documentation, I created a rule

function (user, context, callback) {
    var namespace = 'https://myayth0.com/';
    context.idToken[namespace + 'app_metadata'] = user.app_metadata;
    context.idToken[namespace + 'user_metadata'] = user.user_metadata;
    context.idToken[namespace + 'roles'] = user.user_metadata.roles;
    context.accessToken[namespace + 'app_metadata'] = user.app_metadata;
    context.accessToken[namespace + 'user_metadata'] = user.user_metadata;
    context.accessToken[namespace + 'roles'] = user.user_metadata.roles;
    callback(null, user, context);
 }

Now I have this data return

(...)
 email_verified
:
(...)
 https://ian:auth0:com/app_metadata
 :
(...)
https://ian:auth0:com/roles
:
https://ian:auth0:com/user_metadata
(...)
:
(...)
picture
:
(...)
sub
:
(...)
updated_at
:
(...)

Now accessing picture or email is easy

     this.user.email, this.user.picture

But how about the role?

   https://ian:auth0:com/roles
     : Array(1)
     0: "admin"
   ..................

Upvotes: 3

Views: 2832

Answers (2)

Ian Adem
Ian Adem

Reputation: 119

const roles = this.user['https://ian:auth0:com/roles']
              this.roles = roles[0]

Upvotes: 1

arcseldon
arcseldon

Reputation: 37125

Please check this Auth0 Community Answer.

Once added to your token and returned to your Client application, it should simply be a case of validating and decoding the token to retrieve the value from the namespaced custom claim key.

You should also check whether it makes sense to have the ROLES information tagged to app_metadata rather than user_metadata (which is modifiable by end user) - and whether it is an ID Token (consumer app) or Access Token (receiving API) that should be responsible for holding the custom claim.

Upvotes: 2

Related Questions