Pablo Cibraro

My notes about software development, security and other stuff.

Auth0 - Enrich ID tokens with custom data

Auth0 uses JWT for representing ID tokens. Those tokens contain a fixed set of standard attributes defined by OpenID Connect (OIDC) protocol such as name, nick_name, or email to name a few.

However, some scenarios might require inject custom attributes to differentiate users and provide different UI experience or functionality.

For example, if you have a multi-tenant platform and you want to group users by tenant in a single Auth0 subscription, the tenant ID could be part of the user profile. This kind of information is usually stored as part of the app_metadata in the user profile as it shouldn't be changed by the user.

Another example is role based authentication. Although this feature is supported in Auth0 for Access Tokens for an API, you might need to know the user's roles in advance to provide different look & feel in the UI. Since the ID token is the first token you get after an user is authenticated, it might also be a good place to inject this information.

Auth0 provides Rules, which represent a programmatic mechanism for injecting that kind of data in an ID or Access token.

The following rule shows how to inject a Tenant ID into the ID token,

function setTenantID(user, context, callback) {

  user.app_metadata = user.app_metadata || {};

  let idTokenClaims = context.idToken || {};

  idTokenClaims[`https://myapp/tenantid`] = 
    user.app_metadata.tenant_id;

  context.idToken = idTokenClaims;

  callback(null, user, context);
}

A role can be injected in similar way,

function setRoles(user, context, callback) {

  const assignedRoles = (context.authorization || {}).roles;

  let idTokenClaims = context.idToken || {};

  idTokenClaims[`https://myapp/role`] = assignedRoles;

  context.idToken = idTokenClaims;

  callback(null, user, context);
}