Skip to content

Auth0 Management API — Programmatic Tenant and User Management

DodaTech Updated 2026-06-28 5 min read

In this tutorial, you will learn about Auth0 Management API. We cover key concepts, practical examples, and best practices to help you master this topic.

The Auth0 Management API provides programmatic access to all tenant configuration and user management operations, enabling automation of user provisioning, role assignment, connection management, and log retrieval.

What You'll Learn

By the end of this lesson you will obtain a Management API token, create and update users, assign roles, manage connections, search logs, and automate common administration tasks.

Why It Matters

Manual management through the Auth0 Dashboard does not scale for applications with thousands of users. The Management API enables automated user lifecycle management, self-service admin panels, and CI/CD integration.

Real-World Use

DodaZIP's admin panel uses the Management API for user management. Support agents can create users, reset passwords, assign roles, and view login history without accessing the Auth0 Dashboard.

flowchart LR
    A[Admin Panel] -->|Management API| Auth0
    B[CI/CD Pipeline] -->|Management API| Auth0
    C[Scheduled Jobs] -->|Management API| Auth0
    Auth0 -->|User CRUD| D[(User Store)]
    Auth0 -->|Configuration| E[Tenant Settings]
    style Auth0 fill:#eb5424,color:#fff

Obtaining a Management API Token

Get an access token for the Management API.

# mgmt_token.py
# Obtain Management API token

import requests
import os

def get_mgmt_token():
    domain = os.getenv("AUTH0_DOMAIN", "your-tenant.us.auth0.com")
    client_id = os.getenv("AUTH0_MGMT_CLIENT_ID", "your-mgmt-id")
    client_secret = os.getenv("AUTH0_MGMT_CLIENT_SECRET", "your-mgmt-secret")
    
    response = requests.post(
        f"https://{domain}/oauth/token",
        json={
            "client_id": client_id,
            "client_secret": client_secret,
            "audience": f"https://{domain}/api/v2/",
            "grant_type": "client_credentials",
        }
    )
    
    if response.status_code == 200:
        token = response.json()["access_token"]
        print("Management API token obtained")
        print(f"Token: {token[:30]}...")
        return token
    else:
        print(f"Failed: {response.text}")
        return None

get_mgmt_token()

User Management

Create, read, update, and delete users programmatically.

# user_management.py
# CRUD operations on users

import requests

def manage_users(mgmt_token):
    domain = os.getenv("AUTH0_DOMAIN", "your-tenant.us.auth0.com")
    headers = {"Authorization": f"Bearer {mgmt_token}", "Content-Type": "application/json"}
    
    # Create a user
    response = requests.post(
        f"https://{domain}/api/v2/users",
        headers=headers,
        json={
            "email": "newuser@example.com",
            "password": "SecurePassword123!",
            "connection": "Username-Password-Authentication",
            "email_verified": True,
            "user_metadata": {"department": "Engineering"},
            "app_metadata": {"plan": "premium"},
        }
    )
    if response.status_code == 201:
        user = response.json()
        print(f"User created: {user['user_id']}")
        print(f"  Email: {user['email']}")
        print(f"  Created: {user['created_at']}")
    
    # Search users
    response = requests.get(
        f"https://{domain}/api/v2/users",
        headers=headers,
        params={"q": "email:*@example.com", "search_engine": "v3"}
    )
    users = response.json()
    print(f"\nFound {len(users)} users matching search")
    
    # Update a user
    user_id = users[0]["user_id"] if users else "auth0|none"
    response = requests.patch(
        f"https://{domain}/api/v2/users/{user_id}",
        headers=headers,
        json={"user_metadata": {"department": "Product"}}
    )
    if response.status_code == 200:
        print(f"User {user_id} updated")
    
    return response.json() if users else None

manage_users("your-mgmt-token")

Role and Permission Management

Assign and revoke roles programmatically.

# role_management.py
# Manage roles and permissions

def manage_roles(mgmt_token):
    domain = os.getenv("AUTH0_DOMAIN", "your-tenant.us.auth0.com")
    headers = {"Authorization": f"Bearer {mgmt_token}", "Content-Type": "application/json"}
    
    # List all roles
    response = requests.get(
        f"https://{domain}/api/v2/roles",
        headers=headers
    )
    roles = response.json()
    print("Available Roles:")
    for role in roles:
        print(f"  {role['name']:20s} | {role.get('description', '')}")
    
    # Assign role to user
    role_id = roles[0]["id"] if roles else None
    user_id = "auth0|user123"
    
    if role_id:
        response = requests.post(
            f"https://{domain}/api/v2/users/{user_id}/roles",
            headers=headers,
            json={"roles": [role_id]}
        )
        print(f"\nRole assigned to user: {response.status_code}")
    
    # Remove role from user
    response = requests.delete(
        f"https://{domain}/api/v2/users/{user_id}/roles",
        headers=headers,
        json={"roles": [role_id]}
    )
    print(f"Role removed from user: {response.status_code}")

manage_roles("your-mgmt-token")

Logs and Monitoring

Query authentication logs for monitoring and auditing.

# log_management.py
# Query Auth0 logs

def query_logs(mgmt_token):
    domain = os.getenv("AUTH0_DOMAIN", "your-tenant.us.auth0.com")
    headers = {"Authorization": f"Bearer {mgmt_token}"}
    
    # Get recent logs
    response = requests.get(
        f"https://{domain}/api/v2/logs",
        headers=headers,
        params={"per_page": 10, "sort": "date:-1"}
    )
    
    logs = response.json()
    print("Recent Auth0 Logs:")
    print(f"  {'Date':25s} | {'Type':25s} | {'Description'}")
    print("  " + "-" * 85)
    for log in logs:
        date = log.get("date", "")[:19]
        log_type = log.get("type", "")
        desc = log.get("description", "")[:40]
        print(f"  {date:25s} | {log_type:25s} | {desc}")
    
    # Get log count
    response = requests.get(
        f"https://{domain}/api/v2/logs",
        headers=headers,
        params={"q": "type:sla", "include_totals": True, "per_page": 0}
    )
    totals = response.json().get("total", 0)
    print(f"\nTotal login attempts: {totals}")

query_logs("your-mgmt-token")

Common Mistakes

  1. Not Caching the management token: Management tokens expire. Cache them and refresh only when expired to avoid unnecessary requests.

  2. Using the wrong API audience: The Management API audience is https://{domain}/api/v2/ with a trailing slash and version.

  3. Making too many requests: The Management API has rate limits. Implement exponential backoff for large operations.

  4. Not scoping the management application: Create a dedicated M2M application for Management API access with only the scopes you need.

  5. Forgetting pagination: User lists and logs are paginated. Always check for next page cursors.

Practice Questions

  1. What is the Management API used for? Programmatic tenant configuration and user management, including CRUD operations on users, roles, connections, and logs.

  2. How do you obtain a Management API token? POST to /oauth/token with client_credentials grant, client_id, client_secret, and audience for the Management API.

  3. How do you create a user via the Management API? POST /api/v2/users with user details including email, password, and connection.

  4. How do you search for users? GET /api/v2/users with a q parameter using Auth0 search query syntax.

  5. Challenge: Create a Python script that synchronizes users from an external HR system to Auth0 using the Management API, creating new users, updating existing ones, and deactivating removed ones.

FAQ

What rate limits apply to the Management API?

Rate limits depend on your plan. Free tier: 30 requests/second, paid plans: higher limits.

Can I use the Management API from a frontend?

No. The Management API requires a client secret. Always use it from a backend service.

How do I handle pagination in the Management API?

Use per_page and page parameters, or cursor-based pagination with the next URL from the response.

What scopes do I need for the Management API?

The default scopes include read:users, update:users, create:users, delete:users, read:roles, update:roles.

Can I export all users via the Management API?

Yes. Paginate through all users with GET /api/v2/users and include_totals=true.

Mini Project

Create an admin service that wraps the Auth0 Management API with functions for user creation, role assignment, user search, log querying, and bulk user import from a CSV file.

class Auth0AdminService:
    def __init__(self, domain, client_id, client_secret):
        self.domain = domain
        self.client_id = client_id
        self.client_secret = client_secret
        self.token = None
    
    def _get_token(self):
        resp = requests.post(f"https://{self.domain}/oauth/token", json={
            "client_id": self.client_id, "client_secret": self.client_secret,
            "audience": f"https://{self.domain}/api/v2/", "grant_type": "client_credentials"
        })
        self.token = resp.json()["access_token"]
        return self.token
    
    def create_user(self, email, password, name):
        token = self._get_token()
        resp = requests.post(f"https://{self.domain}/api/v2/users",
            headers={"Authorization": f"Bearer {token}"},
            json={"email": email, "password": password, "name": name, "connection": "Username-Password-Authentication"}
        )
        return resp.json()

service = Auth0AdminService("tenant.us.auth0.com", "client_id", "client_secret")
print(f"Admin service initialized for domain: {service.domain}")

What's Next

Next: Auth0 React for integrating with React apps.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro