Action for assigning default Role does not work

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,

Welcome to the Auth0 Community!

event.stats is not available in post registration actions. Actions Triggers: post-user-registration - Event Object

You probably want to do this in a post login action anyways, as post registration only runs for DB users, and is meant for async flows like adding the ID to a remote system.

Hope this helps!

1 Like

Thanks for your comments, I already modified my code according to similar snippets in other topics.
Also I am using Post registration as I am going to use only Passwordless clients, which are valid for this type as well.

Currently my code does not work because of Auth0 bug Post-user-registration trigger for actions not called - #15 by tyf

Hmm, you shouldn’t be able to use an event.stats.logins_count object regardless. That should be throwing an error as event.stats doesn’t exist.

As I mentioned, you can resolve this issue by using a post-login action instead. It looks like the code you found was for a post-login action (hence the event.stats.logins_count).

The bug you are citing affects the logs and shouldn’t be throwing this error. How do you know the bug is the source of the issue?

1 Like

My current code looks like this (clientId, ClientSecret belongs to Machine-ToMachine application with Auth0 System API access enabled)

exports.onExecutePostUserRegistration = async (event) => {
  const ManagementClient = require("auth0").ManagementClient;

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


  const defaultRole = { id: event.secrets.defaultRoleId };

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

  try {
    await management.roles.assignUsers(defaultRole, data);
  } catch (e) {
    console.error(e);
  }

};

And with this code this action is not executed on PostRegistration for Passwordless user, no running events are listed in the logs

It looks like you are still using a post registration action here.

Try switching to a post login action with your conditional, as I have suggested previously.

Can you please explain the benefits of using your approach? Except the obvious fact that it works now, while PostRegister not due to Auth0 issue

Post-registration actions aren’t designed to update users in Auth0.

Have you looked at the bug report that you linked? It is just a logging bug, it shouldn’t have any impact on whether or not the action fires.

Hm you are right.
Then it’s not clear for me why this code does not work.

Also thanks for your link, I will change code to use another qaction for that.

A post was split to a new topic: Pre registration Action does not add metadata

With the great help from @dan.woda here is working solution to assign new users to specific role and also include this role

  1. Create Machine-to-Machine application with client_credentials grant and access to Auth0 System API
  2. Create Post-Login action with following secrets from M2M application - DOMAIN, CLIENT_ID, SECRET, DEFAULT_ROLE_ID, DFAULT_ROLE_NAME
  3. Create action with this code and assign it to the flow. Note: I am using .NET Core app so have to put claims in specific namespace to make them available for consuming API

/**

* Handler that will be called during the execution of a PostLogin flow.

*

* @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) => {

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

  if (event.authorization && event.authorization.roles.length === 0) {

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

    const auth0 = new ManagementClient({

      domain: event.secrets.DOMAIN,

      clientId: event.secrets.CLIENT_ID,

      clientSecret: event.secrets.CLIENT_SECRET,

      scope: 'read:roles update:users create:role_members',

    })

    const params = {id: event.user.user_id}

    const data = {'roles':[event.secrets.DEFAULT_ROLE_ID]}

    await auth0.assignRolestoUser(params,data,(err) => {

      if (err) {

        console.log('DefaultRoleActionError: ', err)

      }

    })

    api.idToken.setCustomClaim(`${namespace}`, event.secrets.DEFAULT_ROLE_NAME);

    api.accessToken.setCustomClaim(`${namespace}`, event.secrets.DEFAULT_ROLE_NAME);

  } else if (event.authorization) {

    api.idToken.setCustomClaim(`${namespace}`, event.authorization.roles);

    api.accessToken.setCustomClaim(`${namespace}`, event.authorization.roles);

  }

};
1 Like