How to assign "admin" role, when new user signs up?

Hello!

I want to assign “admin” role the new user who signup through auth0 dashboard. All users who will be created by admin, will be assigned roles by admin to them. So when the users created by admin, login through dashboard, they should still have the roles assigned by admin and not the role “admin” itself.
So in short, only the users who signup through dashboard should have “admin” role and rest of users role is decided by admin.

Please suggest how this default role assignment can be done during signup.

Hi @chetanbc,

Thanks for reaching out to the Auth0 Community!

I recommend using the Management API’s Assign roles to a user endpoint inside an Auth0 Pre-registration Action script to assign your users to the “admin” role.

Here is a sample:

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

  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" : ["ROLE_ID"]};

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

I recommend checking out our How can I use the Management API in Actions? FAQ for more instructions.

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

Thanks,
Rueben

Hi @rueben.tiow ,

Thank you for the reply. But I am getting error message about ‘user_id’ not being present in event.user object. What am I missing here? Is it because the user_id is not present before the registration?

Property ‘user_id’ does not exist on type ‘{ username?: string | undefined; email?: string | undefined; app_metadata?: AppMetadata0 | undefined; user_metadata?: UserMetadata0 | undefined; name?: string | undefined; … 4 more …; picture?: string | undefined; }’.

Hi @chetanbc,

Thank you for your response and for testing this for me.

After checking the Pre User Registration Action’s event object, I can confirm that the user_id is unobtainable.

In this case, I made an adjustment to the code to use a Post User Registration Action. This should fix the issue.

Please let me know how this goes for you.

Thanks,
Rueben

Hi @rueben.tiow ,

Thanks for the modifications. It does add roles to user. But it assigns role to both users registered through ‘auth0 login page’ and users created by admin. I wanted to achieve the former only.

I guess the best way for me is to create some button in frontend, say, “get paid account” and when user actually clicks it, I can internally call management api to assign the Admin role. And of-course the user can get paid account only if he pays for it.

Anyhow thanks for your inputs.

Hi @chetanbc,

Thank you for your response.

It may be possible to do this if the admin creates these users with some user_metadata value, for example "created_by_admin": true, and using it in the Action to check if this condition is false.

if(!event.user.user_metadata.created_by_admin){
  try {
    const res = await management.assignRolestoUser(params, data)
  } catch (e) {
    console.log(e)
    // Handle error
  } 
}

That sound’s good!

Please reach out again if you have any questions.

Thanks,
Rueben

Hi everyone,

We wanted to provide an update and some additional information as to how this implementation can be accomplished, in case others come across the same issue.

I understand that you wish to implement a flow where users who signup from the Auth0 Dashboard are granted the Admin role, while the access level for users created by Tenant Administrators are decided by the Admins - no role or permissions are automatically assigned.

Root cause

Implementing this workflow requires distinguishing between a self-signup user (who registers directly through your application’s Auth0 Universal Login page) and an admin-created user (whom an administrator invites or manually provisions via the Auth0 Dashboard / Management API).

Because both types of user creation trigger the post-registration flows, the recommended way to solve this is to use Auth0 Actions combined with a custom user metadata flag .

Official Solution Strategy

  1. Admin-Created Users: When the admin creates a user (via the Auth0 Dashboard or by calling the Management API programmatically), they must pass a specific flag in the user’s user_metadata (for example: "created_by_admin": true) .

  2. Default Role Action (Post-Login): Create a synchronous Post-Login Action . This Action checks if this is the user’s very first login .

    • If they do not have the "created_by_admin": true flag in their metadata, it means they signed up themselves . The action will programmatically assign them the "admin" role;

    • If they do have the "created_by_admin": true flag, the Action skips assigning them the "admin" role, allowing whatever roles the admin manually assigned to remain untouched .

Step-by-Step Implementation

Step 1: Create a Machine-to-Machine (M2M) Application

Because assigning roles inside an Action requires communicating with Auth0’s Management API, you must authorize your action to make these edits .

  1. Go to the Auth0 Dashboard > Applications > Applications and click Create Application;

  2. Choose Machine to Machine Applications and give it a name (e.g., M2M-Action-Role-Assigner);

  3. Select the Auth0 Management API as the API to authorize;

  4. Grant the following permission/scope:

    • update:users (to set metadata if needed)
    • read:roles (to find roles)
    • create:role_members (to assign roles to users)
  5. Click Authorize and copy the Domain, Client ID, and Client Secret of this M2M application from its Settings tab.

Step 2: Create the default “admin” role

  1. Go to User Management > Roles and click + Create Role;

  2. Name it admin and write down its Role ID (e.g., rol_abc123...).

Step 3: Write the Post-Login Action

Using the Login flow is the most reliable way to handle roles. This is because it runs synchronously, ensuring that by the time the user completes their very first login redirect, their roles are already populated inside their issued ID/Access tokens.

  1. Navigate to Actions > Library > click Build Custom;

  2. Name it Assign Admin Role to Self-Signups;

  3. Set the Trigger to Login / Post Login and click Create;

  4. In the code editor, click the Keys icon (Secrets) on the left and define three secrets:

    • M2M_CLIENT_ID
    • M2M_CLIENT_SECRET
    • AUTH0_DOMAIN
  5. Paste the following Node.js code :

const { ManagementClient } = require('auth0');

exports.onExecutePostLogin = async (event, api) => {
  // 1. Only run this logic during the user's very first login
  const isFirstLogin = event.stats.logins_count === 1;
  
  if (!isFirstLogin) {
    return;
  }

  // 2. Check if the user was created by an admin
  const isCreatedByAdmin = event.user.user_metadata && event.user.user_metadata.created_by_admin === true;

  if (isCreatedByAdmin) {
    console.log(`User ${event.user.user_id} was created by an admin. Skipping default role assignment.`);
    return;
  }

  // 3. Initialize the Management API Client using our M2M Secrets
  const management = new ManagementClient({
    domain: event.secrets.AUTH0_DOMAIN,
    clientId: event.secrets.M2M_CLIENT_ID,
    clientSecret: event.secrets.M2M_CLIENT_SECRET,
  });

  // 4. Assign the "admin" role to the self-signup user
  const ROLE_ID = 'YOUR_ADMIN_ROLE_ID_HERE'; // Replace with your actual Admin Role ID

  try {
    await management.users.assignRoles(
      { id: event.user.user_id },
      { roles: [ROLE_ID] }
    );
    console.log(`Successfully assigned default admin role to self-signup user: ${event.user.user_id}`);
  } catch (error) {
    console.error(`Failed to assign default admin role:`, error);
  }
};

  1. Click Deploy;

  2. Go to Actions > Flows > Login, find your newly created custom action under the Custom tab, and drag-and-drop it into your login pipeline. Click Apply.

How to handle user provisioning in this setup

With the Action deployed, you must manage how users are created depending on their origin:

Scenario A: The User signs up themselves (Universal Login Dashboard)

The user visits your app’s signup page, inputs their details, and signs up.

  • Their profile is created without any special metadata;

  • When they authenticate for the first time, logins_count === 1;

  • The Action finds no created_by_admin: true flag and automatically grants them the admin role.

Scenario B: The Admin creates a user manually

Whether using the Auth0 Management API (POST /api/v2/users) or custom admin panels, the admin must explicitly pass the metadata flag :

Example JSON Payload for API Creation:

{
  "email": "employee@company.com",
  "connection": "Username-Password-Authentication",
  "password": "TemporarySecurePassword123!",
  "user_metadata": {
    "created_by_admin": true
  },
  "email_verified": true
}
  • Because created_by_admin is set to true, when this user logs in for the first time, the Action detects the flag and skips the admin role assignment;

  • The user will only have the custom roles manually selected/assigned to them by your administrator in the Auth0 dashboard.

Note on Auth0 UI Manual Creation: If the admin manually creates users strictly through the Auth0 Dashboard UI (instead of your own admin console calling the API), they must manually go to the user’s profile settings immediately after creation, look for the Metadata section, and add {"created_by_admin": true} to the user_metadata before the user performs their first login.

We hope this information helped you with your implementation!

Have a great one,
Gerald