How to attach values to user metadata on automatic migration?

I am currently running an auth0 automatic migration proccess.
When user logs in, the following script is ran by auth0:

function login(username, password, callback) {
  const request = require('request');
  const namespace = '*****';
    url: 'https://********/api/profile',
    auth: {
      username: username,
      password: password
    //for more options check:
  }, function(err, response, body) {
    if (err) return callback(err);
    if (response.statusCode === 401) return callback();
    const user = JSON.parse(body);

    callback(null, {
      user_id: user.user_name.toString(),
      first_name: user.first_name,
      last_name: user.last_name,
      position: user.position,
      organization: user.organization,
      phone_number: user.phone_number,
      icon_url: user.icon_url

The problem is, I can only attach fields to idtoken only from user_metadata (or app_metadata), and those fields set on post-login script showed above aren’t set on user_metadata.

My question is: How do I set those fields to user_metadata on that script?

Hi @dudumonteiro,

Thanks for reaching out to the Auth0 Community!

I understand that you would like to append data to the user’s user_metadata automatically when they migrate.

Since users that automatically migrate need to log in at least once, I recommend using a Post-Login Action script to add user_metadata to the user’s profile.

For example:

 * @param {Event} event - Details about the user and the context in which they are logging in.
 * @param {PostLoginAPI} api - Interface whose methods can be used to change the behavior of the login.
exports.onExecutePostLogin = async (event, api) => {
  api.user.setUserMetadata("favorite_color", "blue");

Hoped this helps!

Please do let me know if you have any additional questions.

Thank you.

Hi @rueben.tiow ,
Thanks for replying.

Unfortunately, I have already tested that Post-Login Action, and didn´t work. I need an actual value from migrated user, not a constant, like “blue”.

exports.onExecutePostLogin = async (event, api) => {
  const namespace = 'https://*********';
  const p_org = event.user.organization;   // it seems this value is null but it appears on auth0 dashboard

  if (event.authorization) {
    api.idToken.setCustomClaim(`${namespace}/user_metadata.organization`, p_org);    

Hi @dudumonteiro,

Thank you for your response.

Have you made sure that your namespaces follow the guidelines explained in our Create Namespaced Custom Claims documentation?

Moreover, the event.user.organization is not a callable property. Instead, use the event.organization property in your Action script.

See here for the complete list of Event Objects callable in a Post Login Action.

Please let me know how this goes.

Thank you.

1 Like