Save SAML Assertion Attribute to user_metadata or app_metadata Using Rules And Actions

Problem Statement:

How to map SAML assertion attributes into the user_metadata or app_metadata on logging in

Solution:

Using Rules

The following rule code accomplishes this request, be sure to change the following:

  • CONNECTION_ID - The connection ID of the SAML connection you want to tie this rule to.
  • ASSERTION_VALUE - The assertion that you want to map into the user’s metadata.
  • METADATA_NAME - The name you want to save the value in the user’s metadata

Also changing the updateUserMetadata function to updateAppMetadata function will save to the app_metadata instead.

function (user, context, callback) {
  user.user_metadata = user.user_metadata || {};

  if (context.connectionID !== '{CONNECTION_ID}') return callback(null, user, context);
  
  user.user_metadata.{METADATA_NAME} = user.{ASSERTION_VALUE};
  
  // persist the user_metadata update
  auth0.users.updateUserMetadata(user.user_id, user.user_metadata)
    .then(function(){
      callback(null, user, context);
    })
    .catch(function(err){
      callback(err);
    });
}

Using Actions:

  • CONNECTION_ID - The connection ID of the SAML connection you want to tie this rule to.
  • ASSERTION_VALUE - The assertion that you want to map into the user’s metadata.
  • METADATA_NAME - The name you want to save the value in the user’s metadata

Each api.user.set… function call can save a single field (can be an array). Duplicate the lines as needed.

exports.onContinuePostLogin = async (event, api) => {
  if (event.connection.id === "{CONNECTION_ID}") {
    api.user.setAppMetadata('{METADATA_NAME}', event.user.{ASSERTION_VALUE});
    api.user.setUserMetadata('{METADATA_NAME}', event.user.{ASSERTION_VALUE});
  }
};