Auth0 Management API — Programmatic Tenant and User Management
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
Not Caching the management token: Management tokens expire. Cache them and refresh only when expired to avoid unnecessary requests.
Using the wrong API audience: The Management API audience is
https://{domain}/api/v2/with a trailing slash and version.Making too many requests: The Management API has rate limits. Implement exponential backoff for large operations.
Not scoping the management application: Create a dedicated M2M application for Management API access with only the scopes you need.
Forgetting pagination: User lists and logs are paginated. Always check for next page cursors.
Practice Questions
What is the Management API used for? Programmatic tenant configuration and user management, including CRUD operations on users, roles, connections, and logs.
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.
How do you create a user via the Management API? POST /api/v2/users with user details including email, password, and connection.
How do you search for users? GET /api/v2/users with a
qparameter using Auth0 search query syntax.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
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