Skip to content

Auth0 Cheat Sheet

Overview

Auth0 is a cloud-based identity platform that provides authentication and authorization services for applications. It supports a wide range of identity protocols including OAuth 2.0, OpenID Connect, and SAML, enabling developers to add secure login, multi-factor authentication, social connections, and role-based access control without building identity infrastructure from scratch.

Auth0 offers universal login pages, passwordless authentication, machine-to-machine tokens, and extensive customization through Actions (serverless functions that run during authentication flows). It integrates with enterprise identity providers, social login platforms, and custom databases, serving both B2C and B2B use cases.

Installation

# Auth0 CLI
# macOS
brew install auth0/auth0-cli/auth0

# Linux
curl -sSfL https://raw.githubusercontent.com/auth0/auth0-cli/main/install.sh | sh

# npm (Node.js SDK)
npm install auth0

# Express.js middleware
npm install express-openid-connect

# React SDK
npm install @auth0/auth0-react

# Next.js SDK
npm install @auth0/nextjs-auth0

# Python SDK
pip install auth0-python

# Verify CLI
auth0 --version

Auth0 CLI

CommandDescription
auth0 loginAuthenticate the CLI
auth0 apps listList applications
auth0 apps createCreate a new application
auth0 apis listList APIs
auth0 apis createCreate an API
auth0 users listList users
auth0 users createCreate a user
auth0 rules listList rules
auth0 logs tailStream real-time logs
auth0 test loginTest login flow
auth0 test tokenGet a test token
# Create an application
auth0 apps create \
  --name "My Web App" \
  --type regular \
  --callbacks "http://localhost:3000/callback" \
  --logout-urls "http://localhost:3000"

# Create an API
auth0 apis create \
  --name "My API" \
  --identifier "https://api.example.com" \
  --scopes "read:users,write:users"

# Get a test token
auth0 test token --audience "https://api.example.com" --scopes "read:users"

Express.js Integration

const { auth, requiresAuth } = require("express-openid-connect");

const config = {
  authRequired: false,
  auth0Logout: true,
  secret: process.env.SESSION_SECRET,
  baseURL: "http://localhost:3000",
  clientID: process.env.AUTH0_CLIENT_ID,
  issuerBaseURL: `https://${process.env.AUTH0_DOMAIN}`,
};

app.use(auth(config));

// Public route
app.get("/", (req, res) => {
  res.send(req.oidc.isAuthenticated() ? "Logged in" : "Logged out");
});

// Protected route
app.get("/profile", requiresAuth(), (req, res) => {
  res.json(req.oidc.user);
});

React Integration

import { Auth0Provider, useAuth0 } from "@auth0/auth0-react";

function App() {
  return (
    <Auth0Provider
      domain={process.env.REACT_APP_AUTH0_DOMAIN}
      clientId={process.env.REACT_APP_AUTH0_CLIENT_ID}
      authorizationParams={{
        redirect_uri: window.location.origin,
        audience: "https://api.example.com",
        scope: "openid profile email read:users",
      }}
    >
      <MyApp />
    </Auth0Provider>
  );
}

function Profile() {
  const { user, isAuthenticated, loginWithRedirect, logout, getAccessTokenSilently } = useAuth0();

  const callApi = async () => {
    const token = await getAccessTokenSilently();
    const response = await fetch("https://api.example.com/users", {
      headers: { Authorization: `Bearer ${token}` },
    });
    return response.json();
  };

  if (!isAuthenticated) {
    return <button onClick={loginWithRedirect}>Log In</button>;
  }

  return (
    <div>
      <p>Welcome, {user.name}</p>
      <button onClick={() => logout({ returnTo: window.location.origin })}>
        Log Out
      </button>
    </div>
  );
}

Management API (Node.js)

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

const management = new ManagementClient({
  domain: process.env.AUTH0_DOMAIN,
  clientId: process.env.AUTH0_M2M_CLIENT_ID,
  clientSecret: process.env.AUTH0_M2M_CLIENT_SECRET,
});

// List users
const users = await management.users.getAll({
  per_page: 10,
  page: 0,
  q: 'email:"*@example.com"',
});

// Create user
await management.users.create({
  connection: "Username-Password-Authentication",
  email: "user@example.com",
  password: "SecureP@ss123!",
  user_metadata: { plan: "premium" },
});

// Update user metadata
await management.users.update({ id: "auth0|user123" }, {
  user_metadata: { plan: "enterprise" },
  app_metadata: { roles: ["admin"] },
});

// Assign roles
await management.users.assignRoles({ id: "auth0|user123" }, {
  roles: ["rol_admin123"],
});

Actions (Serverless Hooks)

// Post-login Action
exports.onExecutePostLogin = async (event, api) => {
  // Add custom claims to token
  const namespace = "https://myapp.com";
  api.idToken.setCustomClaim(`${namespace}/roles`, event.user.app_metadata.roles);
  api.accessToken.setCustomClaim(`${namespace}/roles`, event.user.app_metadata.roles);

  // Deny access based on conditions
  if (!event.user.email_verified) {
    api.access.deny("Please verify your email before logging in.");
  }

  // Add metadata
  api.user.setAppMetadata("last_login", new Date().toISOString());
  api.user.setUserMetadata("login_count",
    (event.user.user_metadata.login_count || 0) + 1
  );
};

Advanced Usage

Machine-to-Machine Authentication

const { AuthenticationClient } = require("auth0");

const auth0 = new AuthenticationClient({
  domain: process.env.AUTH0_DOMAIN,
  clientId: process.env.AUTH0_M2M_CLIENT_ID,
  clientSecret: process.env.AUTH0_M2M_CLIENT_SECRET,
});

const { data } = await auth0.oauth.clientCredentialsGrant({
  audience: "https://api.example.com",
});
console.log(data.access_token);

Organizations (B2B)

// Login with organization
loginWithRedirect({
  authorizationParams: {
    organization: "org_acmecorp",
  },
});

// Management API - create organization
await management.organizations.create({
  name: "acme-corp",
  display_name: "Acme Corporation",
  branding: { logo_url: "https://acme.com/logo.png" },
});

Custom Database Connection

// Login script for custom DB
function login(email, password, callback) {
  const bcrypt = require("bcrypt");
  const MongoClient = require("mongodb").MongoClient;

  MongoClient.connect("mongodb://...", function (err, client) {
    const db = client.db("mydb");
    db.collection("users").findOne({ email }, function (err, user) {
      if (!user) return callback(new WrongUsernameOrPasswordError(email));
      bcrypt.compare(password, user.password, function (err, isValid) {
        if (!isValid) return callback(new WrongUsernameOrPasswordError(email));
        callback(null, { user_id: user._id.toString(), email: user.email });
      });
    });
  });
}

Configuration

# Environment variables
export AUTH0_DOMAIN="your-tenant.auth0.com"
export AUTH0_CLIENT_ID="your-client-id"
export AUTH0_CLIENT_SECRET="your-client-secret"
export AUTH0_AUDIENCE="https://api.example.com"
export AUTH0_CALLBACK_URL="http://localhost:3000/callback"

Troubleshooting

IssueSolution
Login redirect loopCheck callback URL matches exactly in Auth0 dashboard settings
Token expiredImplement token refresh; check tokenExpirationTime settings
CORS errorsAdd your app’s origin to Auth0 Allowed Web Origins
Social login failsVerify social connection credentials in Auth0 dashboard
User not foundCheck the connection name; users exist per-connection
Actions not triggeringVerify Action is deployed and attached to the correct trigger
M2M token failsEnsure API is authorized for the M2M application
Rate limitedImplement caching for Management API tokens; batch operations