# Post Registration Event assign roles to registered user

**URL:** <https://community.auth0.com/t/post-registration-event-assign-roles-to-registered-user/80421>\
**Category:** Get Help\
**Created:** [March 23, 2022, 6:06pm UTC](https://community.auth0.com/t/post-registration-event-assign-roles-to-registered-user/80421 "2022-03-23T18:06:25Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![kcwardwell](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/kcwardwell/32/35704_2.png) [@kcwardwell](https://community.auth0.com/u/kcwardwell)\
**Post date:** [March 23, 2022, 6:06pm UTC](https://community.auth0.com/t/post-registration-event-assign-roles-to-registered-user/80421/1 "2022-03-23T18:06:25Z")

</div>

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

```auto
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?

---

<div class="post-metadata">

**Author:** ![rueben.tiow](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/rueben.tiow/32/11646_2.png) [@rueben.tiow](https://community.auth0.com/u/rueben.tiow)\
**Post date:** [March 23, 2022, 9:04pm UTC](https://community.auth0.com/t/post-registration-event-assign-roles-to-registered-user/80421/3 "2022-03-23T21:04:39Z")

</div>

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:

```auto
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](https://auth0.github.io/node-auth0/ManagementClient.html#assignRolestoUser) documentation helpful.

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

Thank you.

---

<div class="post-metadata">

**Author:** ![lonli.lokli](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/lonli.lokli/32/35271_2.png) [@lonli.lokli](https://community.auth0.com/u/lonli.lokli)\
**Post date:** [March 27, 2022, 10:54am UTC](https://community.auth0.com/t/post-registration-event-assign-roles-to-registered-user/80421/4 "2022-03-27T10:54:17Z")

</div>

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",_

```auto
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);
  }

};

```

---

<div class="post-metadata">

**Author:** ![rueben.tiow](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/rueben.tiow/32/11646_2.png) [@rueben.tiow](https://community.auth0.com/u/rueben.tiow)\
**Post date:** [March 28, 2022, 5:26pm UTC](https://community.auth0.com/t/post-registration-event-assign-roles-to-registered-user/80421/5 "2022-03-28T17:26:22Z")

</div>

Hi @lonli.lokli,

Thank you for your response.

> [@lonli.lokli](#):
>
> ```auto
> if (event.stats.logins_count !== 1) {
> return;
> }
> 
> ```

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](https://auth0.com/docs/customize/actions/flows-and-triggers/post-user-registration-flow/event-object) and [Post Login Event Object](https://auth0.com/docs/customize/actions/flows-and-triggers/login-flow/event-object) to compare the different callable properties.

> [@lonli.lokli](#):
>
> ```auto
> if (!event.user.email_verified) {
> return;
> }
> 
> ```

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.

---

<div class="post-metadata">

**Author:** ![lonli.lokli](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/lonli.lokli/32/35271_2.png) [@lonli.lokli](https://community.auth0.com/u/lonli.lokli)\
**Post date:** [March 29, 2022, 7:45am UTC](https://community.auth0.com/t/post-registration-event-assign-roles-to-registered-user/80421/6 "2022-03-29T07:45:33Z")

</div>

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

 ![image](https://global.discourse-cdn.com/auth0/original/3X/4/8/482c56ffcce5cdd0e4fefc6686424f1b9d139a3a.png)  
 ![image](https://global.discourse-cdn.com/auth0/original/3X/4/f/4f386f16b989b802869cab389f4e789ff8469c7d.png)

---

<div class="post-metadata">

**Author:** ![kcwardwell](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/kcwardwell/32/35704_2.png) [@kcwardwell](https://community.auth0.com/u/kcwardwell)\
**Post date:** [March 29, 2022, 4:21pm UTC](https://community.auth0.com/t/post-registration-event-assign-roles-to-registered-user/80421/7 "2022-03-29T16:21:18Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![lonli.lokli](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/lonli.lokli/32/35271_2.png) [@lonli.lokli](https://community.auth0.com/u/lonli.lokli)\
**Post date:** [March 29, 2022, 8:26pm UTC](https://community.auth0.com/t/post-registration-event-assign-roles-to-registered-user/80421/8 "2022-03-29T20:26:21Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![lonli.lokli](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/lonli.lokli/32/35271_2.png) [@lonli.lokli](https://community.auth0.com/u/lonli.lokli)\
**Post date:** [March 29, 2022, 9:17pm UTC](https://community.auth0.com/t/post-registration-event-assign-roles-to-registered-user/80421/9 "2022-03-29T21:17:55Z")

</div>

Seems like my issue is Auth0 bug

> [@Post-user-registration trigger for actions not called](https://community.auth0.com/t/post-user-registration-trigger-for-actions-not-called/70262/15):
>
> Ahh ok thanks for the heads up! I was just relying on our logging myself so this is good to know +1

---

<div class="post-metadata">

**Author:** ![rueben.tiow](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/rueben.tiow/32/11646_2.png) [@rueben.tiow](https://community.auth0.com/u/rueben.tiow)\
**Post date:** [March 29, 2022, 10:54pm UTC](https://community.auth0.com/t/post-registration-event-assign-roles-to-registered-user/80421/10 "2022-03-29T22:54:39Z")

</div>

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.

 ![image](https://global.discourse-cdn.com/auth0/original/3X/f/d/fda55b9e4b2c96f9f58cb16969d2c0d6a5e44cd3.png)  
Please don’t forget to save your settings.

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

Thank you.

---

<div class="post-metadata">

**Author:** ![kcwardwell](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/kcwardwell/32/35704_2.png) [@kcwardwell](https://community.auth0.com/u/kcwardwell)\
**Post date:** [April 1, 2022, 11:00am UTC](https://community.auth0.com/t/post-registration-event-assign-roles-to-registered-user/80421/11 "2022-04-01T11:00:18Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![rueben.tiow](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/rueben.tiow/32/11646_2.png) [@rueben.tiow](https://community.auth0.com/u/rueben.tiow)\
**Post date:** [April 6, 2022, 12:09am UTC](https://community.auth0.com/t/post-registration-event-assign-roles-to-registered-user/80421/13 "2022-04-06T00:09:30Z")

</div>

Hi @kcwardwell,

Thank you for your response.

> [@kcwardwell](#):
>
> How do I set the Client Credentials Grant flow in Single Page Applications?

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.

---

<div class="post-metadata">

**Author:** ![konrad.sopala](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/konrad.sopala/32/13516_2.png) [@konrad.sopala](https://community.auth0.com/u/konrad.sopala)\
**Post date:** [December 22, 2022, 11:37am UTC](https://community.auth0.com/t/post-registration-event-assign-roles-to-registered-user/80421/14 "2022-12-22T11:37:46Z")

</div>


