Auth0-angular access to users role

Hello! I’m very new to auth0. Im building this website in Angular with express node.js backend. I followed the tutorials to make login/logout and signup for my website, and now based on the user that has logged in the website, I want to render different parts.

I assigned my users “Admin”, and “User”, but for some reason after researching I haven’t got a solution. I can’t access the logged on user’s role.

In Angular I have a my auth0 service:

import { NgModule } from '@angular/core';
import { provideAuth0 } from '@auth0/auth0-angular';

@NgModule({
  providers: [
    provideAuth0({
      domain: 'XXXXXXXXXXX.eu.auth0.com',
      clientId: 'XXXXXXXXXXXXXXXX',
      authorizationParams: {
        redirect_uri: window.location.origin
      }
    })
  ]
})
export class Auth0Module {}

In the component I want to show the user’s role, in the .ts file I do this:

 user$ = this.auth.user$;
  code$ = this.user$.pipe(map((user) => JSON.stringify(user, null, 2)));

and on the .html file I get the user’s info with {{ user.nickname }}.

Also I used the Auth0 Authorization Extension and assigning Roles to my Users from there, gives the app_metadata this:

{
  "authorization": {
    "roles": [
      "Admin"
    ]
  }
}

How can I get the user’s role that I assigned from the auth0 dashboard? Or how can I have access to the logged user app_metadata to fetch the role from there?

Any help would be appreciated. Thanks in advance!

If you need more info so you can understand my problem and the level I am, let me know.

1 Like

Hi @gxomalis,

Welcome back to the Auth0 Community and sorry for the late reply.

Firstly you’ll have to Add user roles to the token, which you can accomplish using an Action as described below:

exports.onExecutePostLogin = async (event, api) => {
  const namespace = 'https://my-app.example.com';
  if (event.authorization) {
    api.idToken.setCustomClaim(`${namespace}/roles`, event.authorization.roles);  
  }
}

Then in your angular application you can display the user profile by accessing the user$ observable on the AuthService instance. This observable already heeds the isAuthenticated$ observable, so you do not need to check if the user is authenticated before using it. Please check our Auth0 Angular SDK for a detailed example.

You can then access the component’s user$ observable from within your template with a property such as user.roles.

Otherwise if you are trying to pass the metadata to your application, you’ll also have to pass that as a custom claim to the ID Token, then use the Management API to get the Get a user’s profile.

This community post should provide information on the matter as well.

Hope this helps the case, but others as well.
Thanks,
Remus

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