How to add Roles and Permissions to the ID Token using Actions?

Problem statement

Is it possible to retrieve the user’s Roles and/or Permissions and include them in the JWT Token?

Solution

Yes, it’s possible to retrieve the user’s Roles and/or Permissions and append them to either the ID Token or Access Token. To do so, you must use a Post-Login Action script.

1.1 Roles

When adding the user’s Roles to the token, call the event.authorization.roles property and add it as a custom claim to the Token. Please see here on creating namespaced custom claims. Below is an example of using a Post Login script to add Roles to the tokens.

/**
* @param {Event} event - Details about the user and the context in which they are logging in.

* @param {PostLoginAPI} api - Interface whose methods can be used to change the behavior of the login.
*/
exports.onExecutePostLogin = async (event, api) => {
  const namespace = 'https://my-app.example.com';
  if (event.authorization) {
    api.idToken.setCustomClaim(`${namespace}/roles`, event.authorization.roles);
    api.accessToken.setCustomClaim(`${namespace}/roles`, event.authorization.roles);
  }
}

1.2 Permissions

For Permissions, you must use the Management API in Actions to call the Get a User’s Permission endpoint to include into the Token.

Note that you can alternatively get the user’s Roles calling the Management API’s Get a user’s roles endpoint.

Reference Materials:

Related FAQs:

4 Likes