Provision Users into Organizations Based on Email Domain in Auth0

Overview

In Business-to-Business (B2B) applications, administrators must often provision users into specific organizations based on the email domain upon the first login. To achieve this seamless onboarding experience, implement an Auth0 Post-Login Action that evaluates the email domain, assigns the user to the corresponding organization, and adds a custom claim to the ID Token.

Applies To
  • Auth0
  • Post-Login Actions
  • Organizations
  • Business-to-Business (B2B) Applications
Solution

To automatically assign users to organizations based on their email domain upon the first login, create a Post-Login Action that extracts the domain from the email address and maps it to a predefined organization ID. The Action then uses the Management API to add the user to that specific organization and sets a custom claim in the ID Token.

Use the provided code snippet to implement this Post-Login Action:

const { ManagementClient } = require('auth0');
exports.onExecutePostLogin = async (event, api) => {
  // 1. Run only on the user's first login.
  if (event.stats.logins_count !== 1) {
    return;
  }
  // 2. Define the mapping from email domain to organization ID.
  const orgMapping = {
    "a.com": "org_xxxxA", // Replace with Organization A's ID
    "b.com: "org_xxxxB", // Replace with Organization B's ID
    "c.com": "org_xxxxC"  // Replace with Organization C's ID
  };
  // 3. Get the user's email domain.
  const domain = event.user.email.split('@')[1];
  const orgId = orgMapping[domain];
  // If the domain doesn't match any organization, stop.
  if (!orgId) {
    console.log(`No organization mapping found for domain: ${domain}`);
    return;
  }
  // 4. Use the Management API to add the user to the organization.
  const managementApi = new ManagementClient({
    domain: event.secrets.DOMAIN,
    clientId: event.secrets.CLIENT_ID,
    clientSecret: event.secrets.CLIENT_SECRET,
  });
  try {
    await managementApi.organizations.addMembers({ id: orgId }, {
      members: [event.user.user_id]
    });
    console.log(`Successfully assigned user ${event.user.user_id} to organization ${orgId}`);
    
    // 5. If successful, set a custom claim in the ID Token.
    api.idToken.setCustomClaim("https://your-app.example.com/new_org_id", orgId);
  } catch (err) {
    console.error(`Error assigning user to organization: ${err}`);
    // api.access.deny('Failed to provision user into an organization.');
  }
};

Recommended content

No recommended content found...