Event.authorization.roles not updated after assigning new roles

After assigning new roles to the user in the organization context, the event.authorization API doesn’t return the new roles assigned but the previous one. Is there a way to “refresh” the event.authorization.roles API to be used within the same action context?

Here’s part of my code:

// previous roles assigned: User

// assign new roles: User, Admin
const params = { id: organizationId, user_id: userId };
const data = { roles: newRoles };
await management.organizations.addMemberRoles(params, data);

// add roles to custom claims:
const roles_namespace = 'https://namespace/claims';

if (event.authorization) {
  api.idToken.setCustomClaim(
    `${roles_namespace}/roles`,
    event.authorization.roles,
  );
  api.accessToken.setCustomClaim(
    `${roles_namespace}/roles`,
    event.authorization.roles,
  );
}

// Instead of returning "User, Admin", the event.authorization.roles keeps returning "User".
1 Like

Hey there @tiago.colombo welcome to the community! Thanks for sharing your code :slight_smile:

I’m currently looking into this: Just to be clear you’d like to add the “Admin” role to an org user and then are expecting to see something like "https://namespace/claims/roles": [ "User", "Admin" ] in the user’s tokens, correct?

Let me know!

Hey @tyf ,

That’s correct. The problem is not adding one more role to the user, but the event.authorization.roles returning it correctly.

1 Like

Thanks for confirming! Unfortunately, after digging into this a bit I believe this is expected behavior.

At the point where the Action is executing, it has already been primed with data that matches the state when the action starts. If you update the state from within the action, this does not update the state for the currently executing Action. So in this case the post-login action starts with 1 role, and the additional role is added, but the Action variable will still have 1 role.

At the next login execution for the user, the state will be loaded again and at this point it will have the updated roles.

The only options I can really think of here are:

  • Once you have added the new role, you’ll need to then fetch the users roles again and use that data to add to your custom claim. Keep in mind this does require another call to the Management API which is subject to rate limits.

  • Another idea might be to rely on the success of the first call to add the role, and then manually add an “admin” custom claim outside of the roles claim. You could potentially rely on this immediately, whereas on subsequent logins you would have the admin role in the event.authorization.roles.

I hope this at least helps give you an idea of what you’re working with :bulb:

Thanks again @tyf.

I had implemented the option 2, but still waiting for your insights to confirm this approach. :+1:

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