Metadata Added on First Login is Missing In SAML Response

Problem statement

With Auth0 as the SAML Identity Provider, app_metadata that is added on a user’s first login in an action is then mapped as an attribute with the SAML 2.0 Addon, but is still missing from the SAML Response Auth0 sends to the Service Provider. This app_metadata does get correctly mapped on all following logins and appears in the SAML Response.

Cause

This behavior is expected. At the end of each trigger’s execution, Actions will update the user profile as a single operation. Internally, this is a call to the Management API to update the user profile. Auth0 does not await the response of the api.user.setAppMetadata() method, so it can take a few milliseconds to complete, and the Action might complete before that.

Solution

There are a couple of approaches to handle this use case.

The first option would be to use the Action to check for the existence of the app_metadata attribute with an if statement . If it is not present in the user profile, add the attribute to the ID token with api.idToken.setCustomClaim(name, value ), and the attribute will then be mapped to the SAML assertion. The name needs to match the one in app_metadata so that the app will recognize it.

Another, more involved solution would be to use the node-auth0 Management Client to update the user’s app_metadata and await the response, instead of using the provided api.user.setAppMetadata() method. See the example below:

var ManagementClient = require('auth0').ManagementClient;
var auth0 = new ManagementClient({
  domain: '{YOUR_ACCOUNT}.auth0.com',
  clientId: '{YOUR_NON_INTERACTIVE_CLIENT_ID}',
  clientSecret: '{YOUR_NON_INTERACTIVE_CLIENT_SECRET}',
  scope: 'update:users update:users_app_metadata update:current_user_metadata,
});

var params = { id: event.user.user_id };
var metadata = {
  my_attribute: 'value'
};

management.users.updateAppMetadata(params, metadata, function (err, user) {
  if (err) {
    // Handle error.
  }

  // Updated user.
  console.log(user);
});

Related Resources: