Post Registration Event assign roles to registered user

I need to assign a role to a user after signup. I am using the following code:

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

exports.onExecutePostUserRegistration= async (event, api) => {

  if (event.stats.logins_count !== 1) {

    return;

  }

  const namespace = "https://agileapp.com/";

  const management = new ManagementClient({

    domain: event.secrets.domain,

    clientId: event.secrets.clientId,

    clientSecret: event.secrets.clientSecret,

    scope: "read:roles create:roles update:roles",

  });

  // const memberRole = { id :'rol_Ov4kxXjqjuYq2uGi'};

  // const adminRole = { id :'rol_4KVILWDGTdBMeSE4'};

  var data = { "users" : [ event.user.user_id]};

  try {

    if (event.authorization) {

      if (!event.user.email) {

        return;

      } else if (event.user.email && event.user.email.endsWith("@smithhorizons.com" || "@theadaptiveceo.com")) {

          api.idToken.setCustomClaim(`${namespace}/roles`, event.secrets.adminRole);

          api.accessToken.setCustomClaim(`${namespace}/roles`, event.secrets.adminRole);

          await management.roles.assignUsers(event.secrets.adminRole, data);

      } else {

          api.idToken.setCustomClaim(`${namespace}/roles`, event.secrets.memberRole);

          api.accessToken.setCustomClaim(`${namespace}/roles`, event.secrets.memberRole);

          await management.roles.assignUsers(event.secrets.memberRole, data);

      }

    }

  } catch (e) {

    console.log(e);

  }

};

What am I doing wrong?

Hi @kcwardwell,

Thanks for reaching out to the Auth0 Community!

After reviewing the code, it seems that there was an improper usage of the management.roles.assignUsers() method. The first parameter passed accepts the role ID of type string. Moreover the event.stats.login_count is not a callable property and should not be needed since the user has 0 logins during this step in the authentication pipeline.

In this case, here is a working example of your solution:

exports. onExecutePostUserRegistration = async (event, api) => {
  const ManagementClient = require('auth0').ManagementClient;

  const namespace = "https://agileapp.com/";

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


const adminRole = { id: event.secrets.adminRole };
const memberRole = { id: event.secrets.memberRole };
var data = { "users" : [ event.user.user_id]};

  try {
    if (event.authorization) {
      if (!event.user.email_verified) {
        return;
      } else if (event.user.email && event.user.email.endsWith("@smithhorizons.com" || "@theadaptiveceo.com")) {
          api.idToken.setCustomClaim(`${namespace}/roles`, event.secrets.adminRole);
          api.accessToken.setCustomClaim(`${namespace}/roles`, event.secrets.adminRole);
          await management.roles.assignUsers(adminRole, data);
      } else {
          api.idToken.setCustomClaim(`${namespace}/roles`, event.secrets. memberRole);
          api.accessToken.setCustomClaim(`${namespace}/roles`, event.secrets. memberRole);
          await management.roles.assignUsers(memberRole, data);
      }
    }
  } catch (e) {
    console.log(e);
  }
  

Lastly, you may find the ManagementClient assignRolestoUser documentation helpful.

Please let me know if there is anything else I can do to help.

Thank you.

I created new Action with 3 secrets - domain (Auth0 domain), clientId & clientSecret with this code

Unfortunately it does not add Role to the User, logs for post registration showing this
on post-user-registration: 400 Compilation failed: Invalid or unexpected token",

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

  const namespace = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role;

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


  const management = new ManagementClient({
    domain: event.secrets.domain,
    clientId: event.secrets.clientId,
    clientSecret: event.secrets.clientSecret,
    scope: "read:roles create:roles update:roles",
  });

  const defaultRole = { id :'rol_MYCUSTOMID'};
  
  var data = { "users" : [ event.user.user_id]};

  try {
    if (event.authorization) {
      if (!event.user.email_verified) {
        return;
      } else {         
          await management.roles.assignUsers(defaultRole, data);
      }
    }
  } catch (e) {
    console.log(e);
  }

};

Hi @lonli.lokli,

Thank you for your response.

First, in your script, I noticed that you are exiting the Action and skipping role assignment if the logins_count is 0. Since this Action executes after a user registers but before they sign in, the user’s logins_count remains 0. Therefore, I recommend removing that if-condition to allow your Action to execute.

Moreover, the event.stats.logins_count is not a callable property when using a Post User Registration Action. It only exists when using a Post Login Action.

See the Post User Registration Event Object and Post Login Event Object to compare the different callable properties.

Similarly, a user signing up has their email_verified status set to false until they verify themselves through the Email Verification. Hence, you should also remove this condition to avoid skipping the role assignment.

Lastly, could you please double-check the values stored in your event.secrets? You could call console.log statements to make sure that the values match the ones found in your application.

Thank you.

Hi @rueben.tiow
thanks for your answer. I’ve modified code according to your comments and it stopped failing. But it also stopped working, eg group is not assigned and I even do not see PostUserRegistration hook in the logs


I have encountered a new issue in this saga. In the PostRegistration event, I am now receiving teh error “**Grant type ‘client_credentials’ not allowed for the client. **”. The code is:

Code ------------------------------------------------------------

var ManagementClient = require(‘auth0’).ManagementClient;

exports.onExecutePostUserRegistration = async (event, api) => {

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

const memberRoles = [“rol_Ov4kxXjqjuYq2uGi”]
const memberData = { “roles”: memberRoles };

var param = { id: event.user.user_id };

console.log(“param”, param)
console.log(‘memberData’, memberData)

try {
await management.assignRolestoUser(param, memberData);

} catch (error) {
console.log(error);
}
};

How do I correct this bug?

Ken

You are using M2M application clientid & cliensecretz right?
Open this application settings, open advanced on bottom and ensure that client_credentials is checked

1 Like

Seems like my issue is Auth0 bug

Hi @kcwardwell,

Thank you for your update.

This issue occurs when the requesting application does not have the Client Credentials grant enabled.

To address this, please navigate to your Auth0 Dashboard > Applications > Applications > YOUR_APP and scroll to the bottom of the settings page, and uncollapse the Advanced settings. On there, click on the Grant Types tab and check the Client Credentials grant type.


Please don’t forget to save your settings.

Once that is complete, you can proceed with the Client Credentials Grant flow.

Thank you.

1 Like

How do I set the Client Credentials Grant flow in Single Page Applications?

1 Like

Hi @kcwardwell,

Thank you for your response.

The suggested solution must use a Machine-to-Machine application to perform the client credentials grant. The M2M app will also need to be granted access to the Management API with all the required scopes (permission).

After that is done, you can request access tokens from the Management API.

Thank you.

1 Like