Auth0 Home Blog Docs

Roles are not being added to JWT access token

rules
roles
access-token

#1

I am authenticating myself in Swagger UI to access protected endpoints. I then get an access token back. I figured out that I need to add an audience to my authorize endpoint to get a JWT token back. But then in my JWT there aren’t any roles present even though I set it by using rules.

function (user, context, callback) {
  user.app_metadata = user.app_metadata || {};
  
  var blacklist = ];
  // You can add a Role based on what you want
  // In this case I check domain
  var addRolesToUser = function(user, cb) {
    if (user.email && blacklist.indexOf(user.email) === -1 && user.email.indexOf('@theledger.be') > -1) {
      cb(null, 'company']);
    } else {
      cb(null, 'user']);
    }
  };

  addRolesToUser(user, function(err, roles) {
    console.log("add roles");
    if (err) {
      console.log("err");
      callback(err);
    } else {
      console.log(roles);
      user.app_metadata.roles = roles;
      auth0.users.updateAppMetadata(user.user_id, user.app_metadata)
        .then(function(){
          console.log("Add role");
          context.idToken.roles = user.app_metadata.roles;
          context.accessToken.roles = user.app_metadata.roles;
          console.log(context.accessToken.roles);
          callback(null, user, context);
        })
        .catch(function(err){
          callback(err);
        });
    }
  });
}

#2

As mentioned in the documentation adding custom claims requires them to be namespaced which means you need to update your rule to add a namespaced claim containing the roles instead of trying to add a custom claim named roles which is not namespaced and as such will be ignored.


#3