Confusion as how to get user roles from Angular SPA

It seems that I got still quite some confusion as how to get the user roles from my Angular SPA.

I am using auth0/auth0-spa-js and have followed the getting started tutorial for Angular applications. Login of users works fine, and I also added the function getTokenSilently$() to retrieve the access_token and put it in requests via Interceptor.

This is my auth0Client

{
    domain: '<MY_DOMAIN>.auth0.com',
    client_id: '<MY_CLIENT_ID>',
    redirect_uri: `${window.location.origin}`,
    scope: 'read:current_user',
    response_type: 'id_token token',
    audience: '<MY_PHP_REST_API_ADDRESS>'
}

I am able to fetch the user roles with following snippet:

getUserRoles$(userID: string): void {
  this.http.get<UserRole[]>(
    `<MY_DOMAIN>.auth0.com/api/v2/users/${userID}/roles`, {
    headers: new HttpHeaders().set('Authorization', `Bearer ${apiToken}`)
  });
}

whereas apiToken is the hard coded test token taken from the auth0 page. However, if I take the access_token from the function getTokenSilently$() and try to get the roles with something like this, I get a 401 Unauthorized.

this.getTokenSilently$().subscribe(token =>
  this.http.get<UserRole[]>(
    `<MY_DOMAIN>.auth0.com/api/v2/users/${userID}/roles`, {
    headers: new HttpHeaders().set('Authorization', `Bearer ${token}`)
  }).subscribe(
    roles => {
      this.userRolesSubject$.next(roles);
      this.roles = roles;
    }
  )
);

My suspicion is that the Management API needs another access_token as my Application API.

Here I read to get the access_token with something like the following:

this.http.post(
  `<MY_DOMAIN>.auth0.com/oauth/token`,
  {
    grant_type: 'client_credentials',
    client_id: '<MY_CLIENT_ID>',
    client_secret: '<MY_CLIENT_SECRET>',
    audience: '<MY_DOMAIN>.auth0.com/api/v2/'
  },
  {
    headers: new HttpHeaders().set('content-type', 'application/x-www-form-urlencoded')
  }
)

but here again, I get the error “access_denied, Unauthorized”.

Obviously I am somehow lost. How can I achieve my goal of retrieving the roles for a specific user?

Hi @tschaika,

Welcome to the Community!

SPAs are limited to a very limited set of permissions against the management API.

Because of this, we can take a different approach to getting user roles. Instead of making an extra call to the management API, we can add the user’s roles to the token.

Sample Use Cases: Rules with Authorization.

Hopefully this solves it!
Dan

1 Like

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