Add roles to user in Custom database migration


I implemented a Login script that retrieves from a legacy database all the information related to users (name, email…), including Roles.
I would like to assign those Roles to the user in the moment it is migrated, so when the Token is generated it will include the permissions for the predefined Role.

  • Can I assign the Roles on the Login Script? If so, can you provide an example.
  • If it is not possible. What other option do I have to accomplish this?


Hi @luis.borge,

Are you migrating that database to Auth0 and you want to migrate the roles? Or are you wanting to just add the role to the user profile during the login script?

If you are doing the latter, you can use app_metadata. Mentioned here.

Hope this helps!


Customer responded via email:


I am trying to do the first and migrate the roles to the Roles and Permissions of Auth0.


I managed to add the Role to the migrated user using a Rule.
On the Login script I add the roles to the app_metada of the user and then I retrieved them in the Rule to add them as Auth0 Roles.
However in the first login the permissions are not loaded in the token. Any ideas?
Here is the code of my rule

function (user, context, callback) {

// short-circuit if the user signed up already or is using a refresh token
if (context.stats.loginsCount > 1 || context.protocol === ‘oauth2-refresh-token’) {
return callback(null, user, context);

const rolesIds = ;

// Role management was introduced in 2.17.0.
// 2.17.1 intermittently returned package not found error.
// Unspecified version didn’t support roles, so must be earlier than 2.17.0
var ManagementClient = require(‘auth0@2.17.0’).ManagementClient;
var management = new ManagementClient({
token: auth0.token,
domain: auth0.domain

var params = {
per_page: 10,
page: 0

management.getRoles(params, function (err, roles) {

for (var i = 0; i < roles.length; i++) {
  if (user.app_metadata.roles.includes(roles[i].name)){

// Update the user's roles
management.assignRolestoUser({ id : user.user_id }, { roles: rolesIds }, (err) => {

  if (!err) {
      console.log('Roles [' + rolesIds.join(', ') + '] assigned to user [' + + ']');
  } else {

  return callback(err, user, context);



This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.