Add a Default Role to a New User on First Login

Last Updated: Apr 8, 2025

Overview

This article clarifies whether it is possible to add a default role to a new user on the first login. Users may need to be created with a specific role.

Applies To

  • Roles
  • New User

Solution

This can be achieved in an Action with the following Post-Login Action code:

  1. Create an Application that will use the Action.

    Screen Shot 2021-06-23 at 12.28.16 PM

  2. Authorize it to the API created with the required scopes. See Enable Role-Based Access Control for APIs.

    Screen Shot 2021-06-23 at 12.29.02 PM

  3. Create an Auth0 Action.

    To get an Action working in a specific flow, create the Action and then add it to a flow.

    1. Navigate to Auth0 Dashboard > Actions > Custom Actions to view the list of existing Actions.
    2. Select Build Custom.
    3. Enter a Name and select the Login / Post Login trigger since an Action will be added to the Login flow.
    4. Then select Create.
  4. Store the application’s credentials in the Action’s event.secrets object.

    Use the domain, client ID, and client secret in the application settings of the app created in step 1. See Add a dependency

    Screen Shot 2021-06-23 at 12.31.34 PM

  5. Add the auth0 npm module/ dependency.

  • See Add a dependency.

    NOTE: Use the latest version of the module, leave the Version textbox blank, click on any other part of the Add Dependency dialog box, and click on the Create button.

    Screen Shot 2021-06-23 at 12.47.31 PM

  1. Initialize and use the Management API in the Action.

    Next, implement the code logic. The following sample code logic assigns a user a role based on their login count.

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

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

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

  const params =  { id : event.user.user_id};
  const data = { "roles" : ["YOUR_ROLE_ID"]};

  try {
    const res = await management.users.assignRoles(params, data)
  } catch (e) {
    console.log(e)
    // Handle error
  }
};
5 Likes