Auth0 Authentication Guide: Setup, Rules, Actions & M2M Tokens
Auth0 is an identity platform that handles authentication and authorization so you don't have to build it yourself. This guide covers everything from initial tenant setup to production-grade patterns: social connections, Universal Login customization, Actions pipelines, M2M tokens for service-to-service auth, and MFA configuration.
Why Auth0 Instead of Building Auth Yourself?
Building authentication from scratch means implementing password hashing (bcrypt/Argon2), secure session management, CSRF protection, OAuth2 flows, token rotation, brute-force protection, and MFA — all of which have subtle security failure modes. A single misconfiguration can expose your entire user base. Auth0 provides all of this as a managed service with a battle-tested implementation, leaving your team to focus on product logic instead of identity infrastructure.
Auth0 is ideal when you need: multiple social providers, enterprise SSO (SAML/OIDC), machine-to-machine API authentication, or compliance features like MFA and log retention. For simple username/password apps that never need external providers, a library like Passport.js or a lighter solution like Clerk may be more appropriate.
Tenant Setup and Application Types
An Auth0 tenant is an isolated environment (like a workspace) that holds your users, applications, and settings. Create separate tenants for development, staging, and production. Within a tenant, you register Applications — each represents a client that will authenticate users:
| Application Type | Use Case | Grant Type |
|---|---|---|
| Regular Web App | Next.js, Express (server-side) | Authorization Code |
| SPA | React, Vue (client-side) | Auth Code + PKCE |
| Native / Mobile | iOS, Android | Auth Code + PKCE |
| Machine to Machine | Backend services, cron jobs | Client Credentials |
Adding Auth0 to an Express / Next.js App
# Install SDK
npm install @auth0/nextjs-auth0
# .env.local
AUTH0_SECRET='use-a-long-random-string'
AUTH0_BASE_URL='http://localhost:3000'
AUTH0_ISSUER_BASE_URL='https://YOUR_DOMAIN.auth0.com'
AUTH0_CLIENT_ID='your-client-id'
AUTH0_CLIENT_SECRET='your-client-secret' // pages/api/auth/[auth0].js — catch-all route
import { handleAuth } from '@auth0/nextjs-auth0';
export default handleAuth();
// pages/_app.js
import { UserProvider } from '@auth0/nextjs-auth0/client';
export default function App({ Component, pageProps }) {
return (
<UserProvider>
<Component {...pageProps} />
</UserProvider>
);
}
// Protected page
import { withPageAuthRequired } from '@auth0/nextjs-auth0';
export default withPageAuthRequired(function Dashboard({ user }) {
return <p>Welcome {user.name}</p>;
}); Social Connections (Google, GitHub)
In the Auth0 Dashboard, go to Authentication > Social and enable connections. For Google, create an OAuth2 app in Google Cloud Console and paste your Client ID + Secret. For GitHub, register an OAuth App at github.com/settings/developers. Auth0 normalizes the profile data across all providers into a consistent user object with sub, email, and name fields.
Rules vs Actions: What Changed
Rules were the original Auth0 pipeline extension — JavaScript functions that ran sequentially after every login. Actions replace them with a cleaner, node-module-based system. Key differences:
| Feature | Rules (deprecated) | Actions (current) |
|---|---|---|
| npm dependencies | Shared, limited list | Any npm package |
| Testing | Manual only | Built-in test runner |
| Secrets | Global configuration | Per-action secrets |
| Triggers | Login only | Login, M2M, Registration, etc. |
// Auth0 Action: Add custom claim to access token
exports.onExecutePostLogin = async (event, api) => {
const namespace = 'https://myapp.com';
const roles = event.authorization?.roles ?? [];
api.accessToken.setCustomClaim(`${namespace}/roles`, roles);
api.idToken.setCustomClaim(`${namespace}/roles`, roles);
}; M2M Tokens for Backend-to-Backend Authentication
# Request an M2M access token (Client Credentials flow)
curl -X POST https://YOUR_DOMAIN.auth0.com/oauth/token \
-H "content-type: application/json" \
-d '{
"client_id": "YOUR_M2M_CLIENT_ID",
"client_secret": "YOUR_M2M_CLIENT_SECRET",
"audience": "https://api.yourapp.com",
"grant_type": "client_credentials"
}'
# Response includes access_token (JWT) and expires_in seconds
# Cache the token; request a new one ~60s before expiry Validate M2M tokens in your API the same way as user tokens — check the iss, aud, and expiry, and verify the signature using Auth0's JWKS endpoint.
MFA Configuration
Enable MFA under Security > Multi-factor Auth. Auth0 supports TOTP (authenticator apps), SMS, WebAuthn (passkeys/hardware keys), and Duo. Use an Action to enforce MFA programmatically for high-risk users:
// Require MFA for admin users
exports.onExecutePostLogin = async (event, api) => {
if (event.authorization?.roles?.includes('admin')) {
api.multifactor.enable('any', { allowRememberBrowser: false });
}
}; Auth0 vs Clerk vs NextAuth Comparison
| Feature | Auth0 | Clerk | NextAuth.js |
|---|---|---|---|
| Free tier | 7,500 MAU | 10,000 MAU | Self-hosted (free) |
| UI components | Universal Login (hosted) | Drop-in React components | Build your own |
| M2M / Client Credentials | Yes | Limited | Manual implementation |
| Enterprise SSO (SAML) | Yes (paid) | Yes (paid) | Via providers |
| Self-hosted option | No | No | Yes |
Related Products
on GumroadDeveloper Productivity Bundle
Stop rebuilding the same setup every project. 51 VSCode snippets, 40 Git aliases, 5 Docker Compose stacks, 5 GitHub Actions workflows, 5 README templates, and a dotfiles kit. Set up a professional dev environment in under an hour.
Buy on Gumroad →AI Prompt Engineering Toolkit
58 structured prompt templates for Claude, ChatGPT, and Gemini — organized by use case. Code Review, Debugging, Documentation, Architecture, and 10 model-specific tips. Stop writing prompts from scratch.
Buy on Gumroad →Developer Cheat Sheet Bundle
10 print-ready cheat sheets for the tools developers use every day: Git, Docker, Linux CLI, SQL, Regex, HTTP Status codes, VS Code shortcuts, Bash scripting, jq/JSON, and Markdown.
Buy on Gumroad →You Might Also Need
JSON Formatter & Validator
Format, beautify, and validate JSON online. Paste your JSON to instantly pretty-print it with 2-space, 4-space, or tab indentation. Minify JSON too. Free, runs in your browser.
Open free tool →
Regex Tester
Free regex tester. Test regular expressions against multiple strings with expected match/no-match assertions — see instant pass/fail results. Built-in presets for email, URL, IPv4, and phone. Pro: unl
Open free tool →
Base64 Encoder & Decoder
Free Base64 Encoder & Decoder. Convert text, images, and any file to Base64 and back. Supports URL-safe Base64, image data URIs, and file download from Base64. Runs 100% in your browser — no data sent
Open free tool →
More Free Tools
Related Articles
curl 深度使用手冊:API 測試從入門到進階
curl 是每位開發者必備的 CLI 工具。本文涵蓋 GET/POST/PUT/DELETE 請求、認證、header 設定、檔案上傳、除錯技巧,以及 REST API 測試的完整實戰範例。
Best AI Code Review Tools 2026: CodeRabbit, Sourcery, DeepCode & Bito Compared
Compare top AI code review tools for 2026: CodeRabbit, Sourcery, DeepCode, and Bito. Features, pricing, GitHub/GitLab integration, and choosing the right tool for your team.
AI Code Review Tools 2026: GitHub Copilot, CodeRabbit, Qodo Merge Ranked
Compare AI code review tools for 2026: GitHub Copilot code review, CodeRabbit, Qodo Merge, Sourcery, and PR-Agent. Pricing, accuracy, and GitHub integration.
AI Coding Tools Comparison 2026: GitHub Copilot vs Cursor vs Windsurf vs Cline
Comprehensive comparison of the best AI coding tools in 2026: GitHub Copilot, Cursor, Windsurf, and Cline. Pricing, features, model support, and real-world benchmarks.
AI Pair Programming in 2026: GitHub Copilot vs Cursor vs Claude Code
Master AI pair programming in 2026. Compare GitHub Copilot, Cursor, and Claude Code for autocomplete, chat, and agentic workflows. Includes setup guides and productivity tips.
Enjoying this tool? Get more like it.
Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.
Unlock AI-Powered Dev Tools
- ⚡ AI Code Review, Doc Generator & SQL Builder
- ⚡ All premium templates & early access
- ⚡ Member discounts on Gumroad products
$9/mo after trial · Cancel anytime
Want the full toolkit?
Get DevPlaybook Pro
Every template, guide, boilerplate, and automation script in one bundle. 13 premium products — grab them all at once and save big.
MIT licensed · Instant download · No subscription
See what's included → Browse all deals →