User Roles in Session Object

Hi @jsdev305

I have tested things around and I managed to have the user assigned default roles and permissions on initial login. The issue is that since the user is being updated after they have logged in, the assigned roles will not be visible in the ID token on the first login. After the user logs in again, these roles will be visible however. You should be able to go around this issue by performing a silent authentication for the user after they have been assigned the roles.

The action code looks something like this:

exports.onExecutePostLogin = async (event, api) => {

  const namespace = "https://yourapp.com/roles";
  let roles = event.authorization.roles;

if (event.authorization && event.authorization.roles && event.authorization.roles.length > 0) {
    api.idToken.setCustomClaim(namespace, roles);
    return;
  }


  const { ManagementClient } = require("auth0");

  const management = new ManagementClient({
    domain: "{{AUTH0_DOMAIN}}",
    clientId: "{{CLIENT_ID}}",
    clientSecret: "{{CLIENT_SECRET}}",
  });

  const params = { id: event.user.user_id };

  try {
    if (roles.length === 0) {
      const data = { roles: ["rol_JO2OS5ByM085bM3l"] };
      await management.users.assignRoles(params, data);
    }
  } catch (e) {
    console.log("Failed to assign or fetch roles:", e);
  }

  // :dart: Add roles to ID token
  api.idToken.setCustomClaim(namespace, roles);
};

Please keep in mind that you will need to enable RBAC for your API in order for the permissions to be assigned to them.

If you have any other questions, let me know!

Kind Regards,
Nik