Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

Auth0 FastAPI SDK

Release Codecov Downloads License Ask DeepWiki

📚 Documentation - 🚀 Getting Started - 💬 Feedback

Documentation

  • Examples - examples for your different use cases.
  • Docs Site - explore our docs site and learn more about Auth0.

Getting Started

1. Features

  • Fully Integrated Auth Flows: Automatic routes for /auth/login, /auth/logout, /auth/callback, etc.
  • Session-Based: Uses secure cookies to store user sessions, either stateless (all data in cookie) or stateful (data in a database).
  • Custom Token Exchange: Exchange tokens from external identity providers or legacy systems for Auth0 tokens, with or without establishing a session.
  • Passkeys: Sign users up and in with WebAuthn passkeys, including email and phone verification at signup.
  • Multiple Custom Domains (MCD): Support for applications using multiple custom domains on the same Auth0 tenant.
  • Account Linking: Optional routes for linking multiple social or username/password accounts into a single Auth0 profile.
  • Backchannel Logout: Receive logout tokens from Auth0 to invalidate sessions server-side.
  • Upstream Session Expiry (IPSIE): Honors the session_expiry claim from enterprise connections as a hard ceiling on the local session.
  • Extensible: Swap in your own store implementations or tune existing ones (cookie name, expiration, etc.)

2. Installation

Requirements: Python 3.9+ and FastAPI. A typical production environment also requires HTTPS so that secure cookies (secure=True) can be sent.

pip install auth0-fastapi

If you're using Poetry:

poetry install auth0-fastapi

3. Setup

Minimal

# main.py
import os
import uvicorn
from fastapi import FastAPI, Depends, Request, Response
from starlette.middleware.sessions import SessionMiddleware

from auth0_fastapi.config import Auth0Config
from auth0_fastapi.auth.auth_client import AuthClient
from auth0_fastapi.server.routes import router, register_auth_routes
from auth0_fastapi.errors import register_exception_handlers

app = FastAPI(title="Auth0-FastAPI Example")

# 1) Add Session Middleware, needed if you're storing data in (or rely on) session cookies
app.add_middleware(SessionMiddleware, secret_key="YOUR_SESSION_SECRET")

# 2) Create an Auth0Config with your Auth0 credentials & app settings
config = Auth0Config(
    domain="YOUR_AUTH0_DOMAIN",          # e.g., "dev-1234abcd.us.auth0.com"
    client_id="YOUR_CLIENT_ID",
    client_secret="YOUR_CLIENT_SECRET",
    app_base_url="http://localhost:3000",  # or your production URL
    secret="YOUR_SESSION_SECRET"
)

# 3) Instantiate the AuthClient
auth_client = AuthClient(config)

# Attach to the FastAPI app state so internal routes can access it
app.state.config = config
app.state.auth_client = auth_client

# 4) Conditionally register routes
register_auth_routes(router, config)

# 5) Include the SDK's default routes
app.include_router(router)


@app.get("/")
def home():
    return {"message": "Hello, Auth0-FastAPI!"}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=3000)

Auth0 Dashboard Configurations

  • The AUTH0_DOMAIN, AUTH0_CLIENT_ID, and AUTH0_CLIENT_SECRET can be obtained from the Auth0 Dashboard once you've created an application. This application must be a Regular Web Application.

  • The SESSION_SECRET is the key used to encrypt the session and transaction cookies. You can generate a secret using openssl:

openssl rand -hex 64
  • The APP_BASE_URL is the URL that your application is running on. When developing locally, this is most commonly http://localhost:3000.

Advanced

If you need more control over session management, transaction cookies, or additional settings, here's a more extensive setup.

By default, the SDK creates:

  • A stateless state store: keeps session data encrypted directly in the cookie, or you can switch to a Stateful store (backed by Redis or another database).
  • A cookie transaction store: for short-lived transaction data.

To tweak these stores - to change cookie names or expiration dates - or to use a custom store, simply instantiate your store and pass it to AuthClient:

# main.py
import os
import uvicorn
from fastapi import FastAPI, Depends, Request, Response
from starlette.middleware.sessions import SessionMiddleware

from auth0_fastapi.config import Auth0Config
from auth0_fastapi.auth.auth_client import AuthClient
from auth0_fastapi.server.routes import router, register_auth_routes
from auth0_fastapi.errors import register_exception_handlers

app = FastAPI(title="Auth0 FastAPI Example")

# 1) Add Session Middleware, needed if you're storing data in (or rely on) session cookies
app.add_middleware(SessionMiddleware, secret_key=os.environ.get("SESSION_SECRET"))

# 2) Create an Auth0Config with your Auth0 credentials & app settings
config = Auth0Config(
    domain="YOUR_AUTH0_DOMAIN",          # e.g., "dev-1234abcd.us.auth0.com"
    client_id="YOUR_CLIENT_ID",
    client_secret="YOUR_CLIENT_SECRET",
    app_base_url="http://localhost:3000",  # or your production URL
    secret="YOUR_SESSION_SECRET",
)

# 3) Instantiate the AuthClient
auth_client = AuthClient(config)

# Attach to the FastAPI app state so internal routes can access it
app.state.config = config
app.state.auth_client = auth_client

# 4) Conditionally register routes
register_auth_routes(router, config)

# 5) Include the SDK's default routes
app.include_router(router)

4. Routes

The SDK for Web Applications mounts 4 main routes:

  1. /auth/login: the login route that the user will be redirected to to initiate an authentication transaction
  2. /auth/logout: the logout route that must be added to your Auth0 application's Allowed Logout URLs
  3. /auth/callback: the callback route that must be added to your Auth0 application's Allowed Callback URLs
  4. /auth/backchannel-logout: the route that will receive a logout_token when a configured Back-Channel Logout initiator occurs

To disable this behavior, you can set the mount_routes option to False (it's True by default):

config = Auth0Config(
    domain="YOUR_AUTH0_DOMAIN",
    client_id="YOUR_CLIENT_ID",
    client_secret="YOUR_CLIENT_SECRET",
    app_base_url="http://localhost:3000",
    secret="YOUR_SESSION_SECRET",
    mount_routes=False,
)

Additionally, by setting mount_connected_account_routes to True (it's False by default) the SDK also can also mount routes useful for using Token Vault with Connected Accounts:

  1. /auth/connect: the route that the user will be redirected to to initiate account linking
  2. /auth/callback: will also handle the callback behaviour from the Connected Accounts flow

Alternatively, by setting mount_connect_routes to True (it's False by default) the SDK also can also mount 4 routes useful for account-linking:

  1. /auth/connect: the route that the user will be redirected to to initiate account linking
  2. /auth/connect/callback: the callback route for account linking that must be added to your Auth0 application's Allowed Callback URLs
  3. /auth/unconnect: the route that the user will be redirected to to initiate account linking
  4. /auth/unconnect/callback: the callback route for account linking that must be added to your Auth0 application's Allowed Callback URLs

These two behaviours cannot be used simultaneously. This form of account-linking is now considered legacy, use of Connected Accounts is preferred.

Usage

Protecting Routes

In order to protect a FastAPI route, you can use the SDK's get_session() method and pass it through Depends:

from fastapi import Depends, Request, Response, HTTPException, status
from auth0_fastapi.config import Auth0Config
from auth0_fastapi.auth.auth_client import AuthClient


config = Auth0Config(
    domain="YOUR_AUTH0_DOMAIN",            # e.g., "dev-1234abcd.us.auth0.com"
    client_id="YOUR_CLIENT_ID",
    client_secret="YOUR_CLIENT_SECRET",
    app_base_url="http://localhost:3000",  # or your production URL
    secret="YOUR_SESSION_SECRET",
    authorization_params={
        "scope": "openid profile",         # required to get user information from Auth0
    }
)

auth_client = AuthClient(config)


@app.get("/profile")
async def profile(request: Request, response: Response, session=Depends(auth_client.require_session)):
    store_options = {"request": request, "response": response}
    user = await auth_client.client.get_user(store_options=store_options)
    if not user:
        return {"error": "User not authenticated"}

    return {
        "message": "Your Profile",
        "user": user,
        "session_details": session
    }

Requesting an Access Token to call an API

If you need to call an API on behalf of the user, you want to specify the audience parameter when registering the plugin. This will make the SDK request an access token for the specified audience when the user logs in.

config = Auth0Config(
    domain="YOUR_AUTH0_DOMAIN",    
    client_id="YOUR_CLIENT_ID",
    client_secret="YOUR_CLIENT_SECRET",
    app_base_url="http://localhost:3000",
    secret="YOUR_SESSION_SECRET"
    auhorization_params= {
      "audience": "YOUR_AUDIENCE"
    }
)

The AUTH0_AUDIENCE is the identifier of the API you want to call. You can find this in the APIs section of the Auth0 Dashboard.

Multiple Custom Domains (MCD)

For applications using multiple custom domains on the same Auth0 tenant, pass a callable instead of a static domain string:

from auth0_server_python.auth_types import DomainResolverContext

async def domain_resolver(context: DomainResolverContext) -> str:
    """Resolve Auth0 domain based on request host."""
    host = context.request_headers.get("host", "").split(":")[0]
    return {
        "brand-1.yourapp.com": "login.brand-1.com",
        "brand-2.yourapp.com": "login.brand-2.com",
    }.get(host, "login.yourapp.com")

config = Auth0Config(
    domain=domain_resolver,  # Callable instead of string
    client_id="YOUR_CLIENT_ID",
    client_secret="YOUR_CLIENT_SECRET",
    app_base_url="https://yourapp.com",
    secret="YOUR_SESSION_SECRET",
)

When using MCD, the SDK automatically:

  • Builds dynamic redirect_uri based on the incoming request host
  • Stores the resolved domain in the session for domain-isolated token refresh
  • Validates tokens against the correct issuer (derived from OIDC metadata)
  • Handles legacy sessions (created before MCD) via a fallback chain

For detailed usage patterns, see examples/MultipleCustomDomains.md.

Session expiry from upstream IdP

When an enterprise connection has "Use ID Token for Session Expiry" enabled, Auth0 emits a session_expiry claim that the SDK enforces as a hard ceiling on the local session - once it passes, the session behaves like "no session" (get_session() / get_user() return None), so require_session and your existing redirect-to-login path handle re-authentication transparently. This requires no application code change.

For detailed behavior and how to read the value, see examples/Sessions.md.

Custom Token Exchange

Exchange a token from an external identity provider or legacy system for Auth0 tokens using RFC 8693 Token Exchange, without a browser redirect, with or without establishing a session.

Building on token exchange, the SDK also supports:

See examples/CustomTokenExchange.md for setup and code samples.

Passkeys

Sign users up and in with WebAuthn passkeys (Touch ID, Face ID, Windows Hello, or a security key) via passkey_signup_challenge(), passkey_login_challenge() and signin_with_passkey(). Signing in stores the session in the same state store as /auth/callback. Pass scope with openid and your audience to signin_with_passkey() to get the same tokens as a regular login.

  • Identifier verification - when your connection requires it, collect an email or phone code at signup and pass it to signin_with_passkey().

Rate-limit the route that requests the signup challenge, because each call sends a code. See Security considerations.

See examples/Passkeys.md for setup and code samples.

Feedback

Contributing

We appreciate feedback and contribution to this repo! Before you get started, please read the following:

Raise an issue

To provide feedback or report a bug, please raise an issue on our issue tracker.

Vulnerability Reporting

Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.

What is Auth0?

Auth0 Logo

Auth0 is an easy to implement, adaptable authentication and authorization platform. To learn more checkout Why Auth0?

This project is licensed under the MIT license. See the LICENSE file for more info.

Metadata

Release files for auth0-fastapi 1.0.0b12

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for auth0-fastapi 1.0.0b12
File Size Uploaded Provenance Actions
auth0_fastapi-1.0.0b12.tar.gz 45.0 kB With provenance Details for auth0_fastapi-1.0.0b12.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for auth0-fastapi 1.0.0b12
File Interpreter ABI Platform Actions
auth0_fastapi-1.0.0b12-py3-none-any.whl Python 3 none any Details for auth0_fastapi-1.0.0b12-py3-none-any.whl

Total release size: 94.5 kB

Release files / auth0_fastapi-1.0.0b12.tar.gz

Download URL auth0_fastapi-1.0.0b12.tar.gz
Size 45.0 kB
Tags Source
SHA-256 checksum
How to use checksums
156dc4f30c40870faeb25514ff0e813f97da201026b7b070bd4d5f17eb81e75f
BLAKE2b-256 checksum
How to use checksums
bc407a0de217f903d18456f0048a8b882ee68523bacd5a28833939c920a43d69
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 26, 2026.

Transparency log

Release files / auth0_fastapi-1.0.0b12-py3-none-any.whl

Download URL auth0_fastapi-1.0.0b12-py3-none-any.whl
Size 49.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1fc2bc700a9fbd29846b2a9e609bee3f35fb2d86957ddd75378ab109f4615d44
BLAKE2b-256 checksum
How to use checksums
a342f5e9a47f206c1ee9c939de2f21a968ca4aadf7229973bec59ebdc2ca7d83
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 26, 2026.

Transparency log

Security for auth0-fastapi 1.0.0b12

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for auth0_fastapi-1.0.0b12.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 26, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page