MCPInstall

auth0-fastapi-api

Use when protecting FastAPI endpoints with JWT Bearer token validation, scope checks, or DPoP binding. Integrates auth0-fastapi-api for stateless APIs receiving access tokens — use even if the user says "secure my FastAPI endpoints" or "validate tokens in FastAPI".

Installs
461
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/auth0/agent-skills --skill auth0-fastapi-api
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads auth0-fastapi-api automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

Auth0 FastAPI API Integration

Protect FastAPI API endpoints with JWT access token validation using auth0-fastapi-api.

Note: This SDK is currently in beta. The API surface may change before the stable 1.0 release. Check PyPI for the latest version. Requires Python >= 3.9 and FastAPI >= 0.115.11.


Prerequisites

  • FastAPI application (Python 3.9+)
  • Auth0 API resource configured (not an Application — must be an API)
  • If you don't have Auth0 set up yet, use the auth0-quickstart skill first

When NOT to Use

  • Server-rendered web applications — Use a session-based login/logout flow instead
  • Single Page Applications — Use auth0-react, auth0-vue, or auth0-angular for client-side auth
  • Mobile applications — Use auth0-react-native or auth0-android
  • Issuing tokens — This skill is for validating access tokens, not issuing them

Quick Start Workflow

1. Install SDK

pip install auth0-fastapi-api python-dotenv

2. Create Auth0 API

You need an API (not Application) in Auth0.

STOP — ask the user before proceeding.

Ask exactly this question and wait for their answer before doing anything else:

"How would you like to create the Auth0 API resource?

  1. Automated — I'll run Auth0 CLI scripts that create the resource and write the exact values to your .env automatically.
  2. Manual — You create the API yourself in the Auth0 Dashboard (or via auth0 apis create) and provide me the Domain and Audience.

Which do you prefer? (1 = Automated / 2 = Manual)"

Do NOT proceed to any setup steps until the user has answered. Do NOT default to manual.

If the user chose Automated, follow the Setup Guide for complete CLI scripts. The automated path writes .env for you — skip Step 3 below and proceed directly to Step 4.

If the user chose Manual, follow the Setup Guide (Manual Setup section) for full instructions. Then continue with Step 3 below.

Quick reference for manual API creation:

# Using Auth0 CLI
auth0 apis create \
  --name "My FastAPI API" \
  --identifier https://my-api.example.com

Or create manually in Auth0 Dashboard → Applications → APIs

3. Configure Environment

Create .env:

AUTH0_DOMAIN=your-tenant.us.auth0.com
AUTH0_AUDIENCE=https://your-api.example.com

AUTH0_DOMAIN is your Auth0 tenant domain (without https://). AUTH0_AUDIENCE is the API identifier you set when creating the API resource in Auth0.

4. Initialize Auth0

import os
from fastapi import FastAPI, Depends
from fastapi_plugin import Auth0FastAPI
from dotenv import load_dotenv

load_dotenv()

app = FastAPI()

auth0 = Auth0FastAPI(
    domain=os.getenv("AUTH0_DOMAIN"),
    audience=os.getenv("AUTH0_AUDIENCE"),
)

Create one Auth0FastAPI instance per application and reuse it across routes. Never hardcode the domain or audience — always use environment variables.

5. Protect Routes

# Require any valid access token
@app.get("/api/private")
async def private(claims: dict = Depends(auth0.require_auth())):
    return {"user": claims["sub"]}

# No authentication required
@app.get("/api/public")
async def public():
    return {"message": "Public endpoint"}

The require_auth() dependency validates the Bearer token, verifies the issuer and audience, and returns the decoded JWT claims.

Error responses:

  • 400 invalid_request — Missing or malformed Authorization header
  • 401 invalid_token — Expired token, invalid signature, wrong issuer/audience
  • 403 insufficient_scope — Valid token but missing required scopes
  • 500 internal_server_error — Unexpected errors

Response body format: {"detail": {"error": "...", "error_description": "..."}}

6. Protect Routes with Scope Checks

# Requires the read:messages scope
@app.get("/api/messages")
async def get_messages(claims: dict = Depends(auth0.require_auth(scopes="read:messages"))):
    return {"messages": []}

# Requires both read:data and write:data scopes
@app.post("/api/data")
async def write_data(claims: dict = Depends(auth0.require_auth(scopes=["read:data", "write:data"]))):
    return {"created": True}

require_auth(scopes=...) checks the scope claim in the JWT. All specified scopes must be present (AND logic). Missing scopes return 403.

7. Access Token Claims

The decoded JWT claims are returned directly from the dependency:

@app.get("/api/profile")
async def profile(claims: dict = Depends(auth0.require_auth())):
    return {
        "sub": claims["sub"],       # user ID
        "scope": claims.get("scope"),  # granted scopes
    }

Key claims:

  • claims["sub"] — user/client ID
  • claims["scope"] — space-separated granted scopes
  • claims["iss"] — issuer (your Auth0 domain URL)
  • claims["aud"] — audience
  • claims["exp"] — expiration timestamp
  • claims["iat"] — issued-at timestamp

8. Protect Routes Without Needing Claims

@app.get("/api/protected", dependencies=[Depends(auth0.require_auth())])
async def protected():
    return {"message": "You need a valid access token to see this."}

9. Test the API

# No token — expect 401
curl http://localhost:8000/api/private

# With a valid access token
curl http://localhost:8000/api/private \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

Get a test token via Client Credentials flow or Auth0 Dashboard → APIs → Test tab.


Common Mistakes

MistakeFix
Hardcoding domain or audience in sourceAlways read from environment variables — never embed credentials in code
Using python-jose or PyJWT directlyNot needed; auth0-fastapi-api handles all validation via JWKS
Manually parsing Authorization headerThe SDK extracts and validates the token automatically
Calling jwt.decode() manuallyThe SDK verifies tokens against the JWKS endpoint — do not verify yourself
Using fastapi-users for Auth0 JWT validationThat package is for user management, not Auth0 JWT verification
Created an Application instead of an API in Auth0Must create an API resource (Applications → APIs) — an Application doesn't issue access tokens with the right audience
Passing domain as full URL with https://domain should be the bare domain, e.g. my-tenant.us.auth0.com, not https://my-tenant.us.auth0.com
Using an ID token instead of an access tokenMust use the access token for API auth — ID tokens are for the client app, not for API authorization
Not configuring CORS for SPA clientsAdd CORSMiddleware to allow requests from your frontend origin
os.getenv() returns None silentlyEnsure python-dotenv is installed and load_dotenv() is called before Auth0FastAPI() initialization — or use os.environ[] to fail fast

DPoP Support

Built-in proof-of-possession token binding per RFC 9449. DPoP is enabled by default in mixed mode (accepts both Bearer and DPoP tokens). See Integration Guide for configuration.


Related Skills

  • auth0-quickstart - Basic Auth0 setup and framework detection
  • auth0-mfa - Add Multi-Factor Authentication
  • auth0-cli - Manage Auth0 resources from the terminal

Quick Reference

Auth0FastAPI configuration:

auth0 = Auth0FastAPI(
    domain=os.getenv("AUTH0_DOMAIN"),       # required (or use domains)
    audience=os.getenv("AUTH0_AUDIENCE"),    # required
    dpop_enabled=True,                       # default; set False for Bearer-only
    dpop_required=False,                     # default; set True to reject Bearer tokens
)

Route protection:

Depends(auth0.require_auth())                    # any valid token
Depends(auth0.require_auth(scopes="read:res"))   # single scope
Depends(auth0.require_auth(scopes=["r", "w"]))   # all scopes required

Accessing claims:

claims["sub"]           # user/client ID
claims["scope"]         # space-separated scopes

Environment variables:

  • AUTH0_DOMAIN — your Auth0 tenant domain (e.g. tenant.us.auth0.com)
  • AUTH0_AUDIENCE — your API identifier (e.g. https://api.example.com)

Common Use Cases:

  • Protect routes → Depends(auth0.require_auth()) (see Step 5)
  • Scope enforcement → Depends(auth0.require_auth(scopes="...")) (see Step 6)
  • DPoP token binding → Integration Guide
  • Reverse proxy setup → Integration Guide
  • Advanced configuration → API Reference

Detailed Documentation

  • Setup Guide — Auth0 CLI setup, environment configuration, getting test tokens
  • Integration Guide — DPoP, scopes, error handling, reverse proxy, testing
  • API Reference — Complete constructor options, method signatures, error codes

References

FAQ

What does the auth0-fastapi-api skill do?

Use when protecting FastAPI endpoints with JWT Bearer token validation, scope checks, or DPoP binding. Integrates auth0-fastapi-api for stateless APIs receiving access tokens — use even if the user says "secure my FastAPI endpoints" or "validate tokens in FastAPI".

How do I install auth0-fastapi-api?

Run npx skills add https://github.com/auth0/agent-skills --skill auth0-fastapi-api in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/auth0-fastapi-api/ (personal) or .claude/skills/auth0-fastapi-api/ (project).

Which AI agents can use auth0-fastapi-api?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is auth0-fastapi-api safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains auth0-fastapi-api?

It is published by auth0 in auth0/agent-skills, and it is an official skill from the maker of the technology it covers. It has 461 recorded installs.

More from auth0/agent-skills

View all →

auth0

auth0/agent-skills

Use when adding, fixing, or improving how an app authenticates users or protects an API, or when using or configuring any Auth0 feature — signing users in and out, sessions and tokens, guarding routes and endpoints, MFA, passwordless passkey login (WebAuthn), SSO, Organizations, RBAC, custom domains, Universal Portals for hosted account and organization self-service, or Universal Login branding. Also use to audit a tenant's health, security, and plan fit (CheckMate), to debug why an auth flow fails, to migrate from another auth provider, or to set up the Vercel native integration. Covers any web, mobile, or backend framework and every Auth0 SDK, tool, and API. Use even if the user never mentions Auth0.

Backend & APIs5.3K installs

auth0-quickstart

auth0/agent-skills

Use when adding Auth0 authentication to any app and unsure which SDK or skill to use. Detects the project's framework and routes to the right setup workflow — use this as the entry point even if the user just says "add login to my app" or "set up Auth0" without naming a framework.

OfficialAI & Agents2.7K installs

auth0-nextjs

auth0/agent-skills

Use when adding Auth0 login, logout, protected pages, or middleware to a Next.js application. Supports App Router and Pages Router with @auth0/nextjs-auth0 — use even if the user says "add login to my Next.js app" or "protect my Next.js routes".

OfficialFrontend & Design1.6K installs

auth0-react

auth0/agent-skills

Use when adding Auth0 login, logout, protected routes, or user sessions to a React SPA. Integrates @auth0/auth0-react — use even if the user says "add login to my React app" or "protect my React routes" without naming the SDK.

OfficialFrontend & Design1.5K installs

auth0-react-native

auth0/agent-skills

Use when adding Auth0 login, logout, or biometric auth to a bare React Native app (not Expo). Integrates react-native-auth0 with native deep linking.

OfficialFrontend & Design963 installs

auth0-express

auth0/agent-skills

Use when adding session-based login, logout, or protected routes to an Express.js web application. Integrates express-openid-connect — use even if the user says "add login to my Express app" or "protect my Express routes".

OfficialBackend & APIs816 installs

Popular backend & apis skills

View category →

find-skills

vercel-labs/skills

Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.

OfficialBackend & APIs4.1M installs

entra-app-registration

microsoft/azure-skills

Guides Microsoft Entra ID app registration, OAuth 2.0 authentication, and MSAL integration. USE FOR: create app registration, register Azure AD app, configure OAuth, set up authentication, add API permissions, generate service principal, MSAL example, console app auth, Entra ID setup, Azure AD authentication. DO NOT USE FOR: Key Vault secrets (use azure-keyvault-expiration-audit), general Azure resource security guidance.

OfficialBackend & APIs566.7K installs

This skill should be used when the user wants to "write agent code", "build an agent with ADK", "add a tool", "create a callback", "define an agent", "use state management" — in a project that needs ADK (Agent Development Kit) API patterns and code examples. It provides a quick reference for agent types, tool definitions, orchestration patterns, callbacks, state management, the graph Workflow API, and reference recipes to study. Do NOT use for scaffolding (use google-agents-cli-scaffold) or deployment (use google-agents-cli-deploy).

Backend & APIs514.8K installs

embedded-captions

heygen-com/hyperframes

Add captions or subtitles to an existing single-subject talking-head video without editing the footage. Use for plain verbatim captions, cinematic captions embedded behind the subject, VFX captions, “炸/特效/酷炫字幕,” or a named identity from the 35-style catalog. Route by visual identity, not by backend engine. The quiet anchor rail is the default; embed every word only when the user explicitly wants a fully cinematic treatment. The workflow runs locally end to end, including transcription and subject matting; split multi-shot footage before applying it.

Backend & APIs453.3K installs

entra-agent-id

microsoft/azure-skills

Provision Microsoft Entra Agent Identity Blueprints, BlueprintPrincipals, and per-instance Agent Identities via Microsoft Graph, and configure OAuth 2.0 token exchange (fmipath, OBO, cross-tenant) including the Microsoft Entra SDK for AgentID sidecar. USE FOR: Agent Identity Blueprint, BlueprintPrincipal, agent OAuth, fmipath token exchange, agent OBO, Workload Identity Federation for agents, polyglot agent auth, Microsoft.Identity.Web.AgentIdentities. DO NOT USE FOR: standard Entra app registration (use entra-app-registration), Microsoft Foundry agent authoring (use microsoft-foundry).

OfficialBackend & APIs336.6K installs

neon

neondatabase/agent-skills

Overview of Neon, a complete set of cloud backend primitives around Lakebase Postgres: Auth, Object Storage, Functions, the AI Gateway, and Realtime. Start here to choose Neon for undecided login, files, APIs, and LLM calls, set up the CLI or MCP server, and follow the branch-first workflow. Use when building an app or backend on Neon, or when "Neon" or "Lakebase Postgres" is mentioned. Child skill neon-postgres wins for an existing DATABASEURL, SQL, schema, inspect, or search. Child skill neon-auth wins for login, users, sessions, identity routing, and Managed Better Auth setup. Child skill neon-realtime wins for live queries in reactive apps and agents. Also use for object storage, S3, buckets, serverless functions, function triggers, cron, AI gateway, LLM calls, realtime, logs, Loki, Grafana, observability, postgres, database, backend, Claimable Neon, neon.new, or a no-signup database.

Backend & APIs237.1K installs