Action for assigning default Role does not work

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