Using another user identifier (UUID) than the user_id

You can make use of the uuid NPM package in rules as a quick way to generate a UUID that can then be assigned to each user.

I’m including a sample rule that upon user login generates a UUID for the user, if one hasn’t been provided yet. After ensuring that every user is provisioned with a UUID the rule also exposes that information in any issued ID token or access token through the means of custom claim.

function (user, context, callback) {
  var uuid = require("uuid");

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

  var promise = Promise.resolve(1);

  if (!user.app_metadata.uuid) {
    user.app_metadata.uuid = uuid();

    promise = auth0.users.updateAppMetadata(user.user_id, user.app_metadata);
  }

  promise.then(() => {
    if (context.idToken) {
      // Include the uuid in the issued ID token if applicable
      context.idToken"http://example.com/uuid"] = user.app_metadata.uuid;
    }

    if (context.accessToken) {
      // Include the uuid in the issued access token if applicable
      context.accessToken"http://example.com/uuid"] = user.app_metadata.uuid;
    }
    
    callback(null, user, context);
  }).catch(callback);
}

Have in mind that the above rule is meant to be used along with the recent OIDC conformance flows and/or API Authorization features. With these flows, custom claims need to be added explicitly to the generated tokens and also have to use a namespace. (for more information check the OIDC-conformant authentication adoption guide)

If you’re not making use of these flows, which would be the case if you used /oauth/ro then you will be able to include custom claims in the issued ID Token by including it the requested scope scope=openid+uuid. In this scenario, namespaces are not required and the uuid claim would be returned if the user contained a matching property with that name either as a root property or as a property of app_metadata. The following revised rule should address the situation you mentioned regarding /oauth/ro:

function (user, context, callback) {
  var uuid = require("uuid");

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

  var promise = Promise.resolve(1);

  if (!user.app_metadata.uuid) {
    user.app_metadata.uuid = uuid();
    user.uuid = user.app_metadata.uuid;

    promise = auth0.users.updateAppMetadata(user.user_id, user.app_metadata);
  }

  promise.then(() => {
    callback(null, user, context);
  }).catch(callback);
}
2 Likes