Post-login Action Not Assigning a Default Role on Login

Problem statement

A post-login Action was created to attach roles to users on first log-in. However, the roles are empty for the user after the first login.

Steps to reproduce

Try the code snippet in a post-login action on auth0@4.0.1:

exports.onExecutePostLogin = async (event, api) => {
  if (event.stats.logins_count !== 1) {
    return;
  }

  const ManagementClient = require('auth0').ManagementClient;

  const management = new ManagementClient({
      domain: event.secrets.domain,
      clientId: event.secrets.clientId,
      clientSecret: event.secrets.clientSecret,
  });

  const params = { id : event.user.user_id};
  const data = { "roles" : ["rol_Y7lJkdHJ9dRUgNNi"]};
  
  try {
    const res = await management.assignRolestoUser(params, data)
  } catch (e) {
    console.log(e)
    // Handle error
  }
};

Troubleshooting

Tried the provided Action code snippet on auth0@4.0.1, the code was not working. Tried downgrading version to 3.6.0, roles were assigned successfully.

Cause

Migration to node-auth0 v4 resulted in some top-level methods being changed, including the assignRolestoUser.

Solution

Several methods have had changes to their names and structure in migration to node-auth0 v4. More information is available about the changes here.

The following updated code snippet should assign a default role at sign-in.

exports.onExecutePostLogin = async (event, api) => {
  if (event.stats.logins_count !== 1) {
    return;
  }

  const ManagementClient = require('auth0').ManagementClient;

  const management = new ManagementClient({
      domain: event.secrets.domain,
      clientId: event.secrets.clientId,
      clientSecret: event.secrets.clientSecret,
  });

  const role =  { id : "YOUR_ROLE_ID_HERE" };
  const data = { "users" : [ event.user.user_id ]};
  
  try {
    const res = await management.roles.assignUsers(role, data);
  } catch (e) {
    console.log(e)
    // Handle error
  }
};

Alternatively, another option is to downgrade your Auth0 dependency version in your Post-Login Action.