Is it really this difficult: Assign roles and put into JWT

Hi all,
I have a SPA that I’ve recently secured access to with Auth0. It was a breeze. :slight_smile:

I want to get my SPA to get Auth0 to generate JWT’s that have a users role signed into them under roles array. - This is proving to be significantly more difficult than I would’ve anticipated. I’ve got it generating a JWT, which is great but no roles are there.

So far I’ve went through what feels like a million steps to fix this and I’m no closer. I originally moved from Okta, as I think the Auth0 JS client and react support on the front-end is a lot better … but what I’m trying to do right now which is to:

  • Automatically give every user a role when they signup
  • Apply their given roles into their JWT

These two steps were a lot easier with OKTA (sorry)

I am trying to use a bunch of different rules to get this to work (based on reading almost everything I could find about doing this). First one is:

This final rule I’m trying is the most interesting:

function (user, context, callback) {
const ManagementClient = require('auth0@2.27.0').ManagementClient;

const management = new ManagementClient({
  token: auth0.accessToken,
  domain: auth0.domain
});

console.log(auth0.accessToken);
const count = context.stats && context.stats.loginsCount ? context.stats.loginsCount : 0;
if (count > 1) {
    return callback(null, user, context);
}


  var params = {
    per_page: 10,
    page: 0
  };

management.getRoles(params, function (err, roles) {
       console.log("roles ARE: ");
   console.log(roles.length);
       console.log(roles);
});

 const userParams =  { id : user.user_id};
const data = { "roles" : ["user"]};

management.assignRolestoUser(userParams, data, function (err, user) {
  if (err) {
    // Handle error.
    console.log(err);
  }
	console.log("success");
callback(null, user, context);
});

This caused me to get a Schema violation - I read this was caused by not giving the role id. So I used the management API to get the roles as above - however the roles are coming back as undefined.

Anyone know why the roles might be coming back as undefined?

Here’s another different rule I tried to achieve the same thing… why are there so many different ways of doing things?

function setRolesToUser(user, context, callback) {

  // Roles should only be set to verified users.
  if (!user.email || !user.email_verified) {
    return callback(null, user, context);
  }

  user.app_metadata = user.app_metadata || {};
  // You can add a Role based on what you want
  // In this case I check domain
  const addRolesToUser = function (user) {
    return ['user'];  // just unconditionally apply the user role
  };

  const roles = addRolesToUser(user);

  user.app_metadata.roles = roles;
  auth0.users.updateAppMetadata(user.user_id, user.app_metadata)
    .then(function () {
    	console.log(context.idToken);
      console.log(context);
      context.idToken['https://example.com/roles'] = user.app_metadata.roles;
      callback(null, user, context);
    })
    .catch(function (err) {
      callback(err);
    });
}

This doesn’t work.

Also trying this to actually write a roles array into the JWT - it doesn’t do anything either:

function (user, context, callback) {
  const namespace = 'roles';
  const assignedRoles = (context.authorization || {}).roles;

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

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

  context.idToken = idTokenClaims;
  context.accessToken = accessTokenClaims;
  callback(null, user, context);
}

Any help would be greatly appreciated.

Update on this. I’ve deleted all my configurations on Auth0 and started again following this tutorial:


and

With a jumbled and confused combo of these I’ve managed to enable auto assign of a role on signup/first login.

However this role is only visible on the “core app” - what I mean is that looking at the user on the main Auth0 app the role shows - yaay - but it’s not showing in the AuthZ extension. Why on earth is that? Why on earth are there effectively two separate applications?

In both cases, the roles are still not showing in the decoded JWT.

Hi @colinjohnriddell,

Welcome to the Community!

Sorry to hear about the frustrating experience with roles. I am going to bring this issue up with the team who manages our docs, as you aren’t the first to mention it. There are a few pieces of info that could make this much clearer. Thank you for the feedback.

As for your issues, let’s see if we can clarify a few things:

  • The RBAC extension vs the RBAC core (the one in your main dashboard) are completely separate features. They have a similar function, but they don’t share data. The extension was built, then the core was built to replace it, but the extension still exists for some legacy users because of the groups feature. In summary, pick one, not both. I would suggest the core unless you absolutely need the extension.
  • As for assign a role on signup, I hope you were able to find this FAQ.
  • And for getting roles in the token, here is a doc that has a sample rule of how to do it. Do not use an auth0 domain as your namespace. https://example.com will work fine.
  • One final tip. The first time your user logs in, they don’t have any roles, the rule that assigns them will add a role, but it won’t show up in the context.authorization object until next login. This means you will have to manually add the role you assigned to the token in your assign a role of first login rule.

If any of this is confusing let me know and I will clarify.

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