Skip to main content

SDK for verifying access tokens and securing APIs with Auth0, using Authlib.

Project description

The Auth0 FastAPI API SDK library allows you to secure FastAPI APIs using bearer tokens from Auth0.

It exposes a simple require_auth dependency that checks if incoming requests have a valid JWT, then provides the token claims to your route handler.

Release Downloads License

📚 Documentation - 🚀 Getting Started - 💬 Feedback

Documentation

  • QuickStart- our guide for adding Auth0 to your Fastapi app.
  • Examples - examples for your different use cases.
  • Docs Site - explore our docs site and learn more about Auth0.

Getting Started

1. Install the SDK

This library requires Python 3.9+.

pip install auth0-fastapi-api

If you’re using Poetry:

poetry install auth0-fastapi-api

2. Configure and Register the Auth0FastAPI Plugin

In your FastAPI application, create an instance of the Auth0FastAPI class. Supply the domain and audience from Auth0:

  • The AUTH0_DOMAIN can be obtained from the Auth0 Dashboard once you've created an API.
  • The AUTH0_AUDIENCE is the identifier of the API that is being called. You can find this in the API section of the Auth0 dashboard.
from auth0_fastapi_api import Auth0FastAPI

# Create the Auth0 integration
auth0 = Auth0FastAPI(
    domain="<AUTH0_DOMAIN>",
    audience="<AUTH0_AUDIENCE>",
)

3. Protecting API Routes

To protect a FastAPI route, use the require_auth(...) dependency. Any incoming requests must include a valid Bearer token (JWT) in the Authorization header, or they will receive an error response (e.g., 401 Unauthorized).

@app.get("/protected-api")
async def protected(
    # The route depends on require_auth returning the decoded token claims
    claims: dict = Depends(auth0.require_auth())
):
    # `claims` is the verified JWT payload (dict) extracted by the SDK
    return {"message": f"Hello, {claims['sub']}"}

How It Works

  1. The user sends a request with Authorization: Bearer <JWT>.
  2. The SDK parses the token, checks signature via Auth0’s JWKS, validates standard claims like iss, aud, exp, etc.
  3. If valid, the route receives the decoded claims as a Python dict (e.g. {"sub": "user123", "scope": "read:stuff", ...}).

[!IMPORTANT]
This method protects API endpoints using bearer tokens. It does not create or manage user sessions in server-side rendering scenarios. For session-based usage, consider a separate library or approach.

Custom Claims

If your tokens have additional custom claims, you’ll see them in the claims dictionary. For example:

@app.get("/custom")
async def custom_claims_route(claims: dict = Depends(auth0.require_auth())):
    # Suppose your JWT includes { "permissions": ["read:data"] }
    permissions = claims.get("permissions", [])
    return {"permissions": permissions}

You can parse or validate these claims however you like in your application code.

4. Advanced Configuration

  • Scopes: If you need to check for specific scopes (like read:data), call require_auth(scopes="read:data") or pass a list of scopes. The SDK will return a 403 if the token lacks those scopes in its scope claim.
@app.get("/read-data")
async def read_data_route(
    claims=Depends(auth0.require_auth(scopes="read:data"))
):
    return {"data": "secret info"}
  • Mocking / Testing: To test locally without hitting Auth0’s actual JWKS endpoints, you can mock the HTTP calls using pytest-httpx or patch the verification method to avoid real cryptographic checks.
Example
from fastapi import FastAPI, Depends
from auth0_fastapi_api import Auth0FastAPI
from fastapi.testclient import TestClient

app = FastAPI()
auth0 = Auth0FastAPI(domain="my-tenant.us.auth0.com", audience="my-api")

@app.get("/public")
async def public():
    return {"message": "No token required here"}

@app.get("/secure")
async def secure_route(
    claims: dict = Depends(auth0.require_auth(scopes="read:secure"))
):
    # claims might contain {"sub":"user123","scope":"read:secure"}
    return {"message": f"Hello {claims['sub']}, you have read:secure scope!"}

# Example test
def test_public_route():
    client = TestClient(app)
    response = client.get("/public")
    assert response.status_code == 200
    assert response.json() == {"message": "No token required here"}

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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

auth0_fastapi_api-1.0.0b1.tar.gz (7.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

auth0_fastapi_api-1.0.0b1-py3-none-any.whl (9.2 kB view details)

Uploaded Python 3

File details

Details for the file auth0_fastapi_api-1.0.0b1.tar.gz.

File metadata

  • Download URL: auth0_fastapi_api-1.0.0b1.tar.gz
  • Upload date:
  • Size: 7.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.2

File hashes

Hashes for auth0_fastapi_api-1.0.0b1.tar.gz
Algorithm Hash digest
SHA256 97f016b6173fd708c925f29d6b29ea6be092bc36dfe31b80d8931561a061b2f3
MD5 c5756dd2c2bd9724b38dd2f41e37cdc7
BLAKE2b-256 94d63d30607224ea755837e402c7320181fbc5ebc9b98dd0e994cdbf03ad4641

See more details on using hashes here.

File details

Details for the file auth0_fastapi_api-1.0.0b1-py3-none-any.whl.

File metadata

File hashes

Hashes for auth0_fastapi_api-1.0.0b1-py3-none-any.whl
Algorithm Hash digest
SHA256 afeb0e0705bd0c17c3ddd58931bb8c0aa7330f18286fdbefb818cd2aa2e83d50
MD5 63d5f83a589016fffadded7bc982a049
BLAKE2b-256 0580dad279b8be78f16957acfdf1f2edeae7d9a5e467aa5a9e1f583556eace05

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page