Auth0 Home Blog Docs

How do I add user permissions to id token?

Question: How do I add user permissions to id token?

Answer:

This can be accomplished in a rule, using the Management API GET /api/v2/users/{id}/permissions endpoint and adding permissions as a custom claim.

User @ryantomaselli wrote this rule to add permissions to an id_token:

function (user, context, callback) {
  var map = require('array-map');
  var ManagementClient = require('auth0@2.17.0').ManagementClient;
  var management = new ManagementClient({
    token: auth0.accessToken,
    domain: auth0.domain
  });

  var params = { id: user.user_id, page: 0, per_page: 50, include_totals: true };
  management.getUserPermissions(params, function (err, permissions) {
    if (err) {
      // Handle error.
      console.log('err: ', err);
      callback(err);
    } else {
      var permissionsArr = map(permissions.permissions, function (permission) {
        return permission.permission_name;
      });
      context.idToken[configuration.NAMESPACE + 'user_authorization'] = {
        permissions: permissionsArr
      };
    }
    callback(null, user, context);
  });
} 

Take note of the use of NAMESPACE in the custom claim:

  • The namespace URL does not have to point to an actual resource because it’s only being used as an identifier; it will not be called.
  • Any non-Auth0 HTTP or HTTPS URL can be used as a namespace identifier, and any number of namespaces can be used.

Supporting Documentation:

Documentation: getUserPermissions, Custom Claims, Custom Claims Example
Community Topic: Accessing the permissions array in the access token

1 Like