Auth0 FastAPI Python SDK
Project description
📚 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).
- 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.
- 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, andAUTH0_CLIENT_SECRETcan be obtained from the Auth0 Dashboard once you've created an application. This application must be aRegular Web Application. -
The
SESSION_SECRETis the key used to encrypt the session and transaction cookies. You can generate a secret usingopenssl:
openssl rand -hex 64
- The
APP_BASE_URLis the URL that your application is running on. When developing locally, this is most commonlyhttp://localhost:3000.
[!IMPORTANT]
You will need to register the following URLs in your Auth0 Application via the Auth0 Dashboard:
- Add
http://localhost:3000/auth/callbackto the list of Allowed Callback URLs- Add
http://localhost:3000to the list of Allowed Logout URLs
Advanced
If you need more control over session management, transaction cookies, or additional settings, here’s a more extensive setup.
Customizing the Cookie Stores
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:
/auth/login: the login route that the user will be redirected to to initiate an authentication transaction/auth/logout: the logout route that must be added to your Auth0 application's Allowed Logout URLs/auth/callback: the callback route that must be added to your Auth0 application's Allowed Callback URLs/auth/backchannel-logout: the route that will receive alogout_tokenwhen 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:
/auth/connect: the route that the user will be redirected to to initiate account linking/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:
/auth/connect: the route that the user will be redirected to to initiate account linking/auth/connect/callback: the callback route for account linking that must be added to your Auth0 application's Allowed Callback URLs/auth/unconnect: the route that the user will be redirected to to initiate account linking/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.
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 get the 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
}
[!IMPORTANT]
The above is to protect server-side rendering routes by the means of a session, and not API routes using a bearer token. Theauthorization_paramspassing thescopeis used in to retrieve the user information from Auth0. Can be omitted if you don't need the user information.
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.
Feedback
Contributing
We appreciate feedback and contribution to this repo! Before you get started, please read the following:
- Auth0's general contribution guidelines
- Auth0's code of conduct guidelines
- This repo's contribution guide
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 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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file auth0_fastapi-1.0.0b5.tar.gz.
File metadata
- Download URL: auth0_fastapi-1.0.0b5.tar.gz
- Upload date:
- Size: 27.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b960168bad32cc6135c4745e917f711a6004ba451400f5244e3bfe2818473eb1
|
|
| MD5 |
70281fa7de3103e5148572af09a18f92
|
|
| BLAKE2b-256 |
df9dd331bb234f849f7d5072752dace803af4d992da11a9784c30a74e61f2a96
|
Provenance
The following attestation bundles were made for auth0_fastapi-1.0.0b5.tar.gz:
Publisher:
publish.yml on auth0/auth0-fastapi
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
auth0_fastapi-1.0.0b5.tar.gz -
Subject digest:
b960168bad32cc6135c4745e917f711a6004ba451400f5244e3bfe2818473eb1 - Sigstore transparency entry: 707643196
- Sigstore integration time:
-
Permalink:
auth0/auth0-fastapi@5a618720076d3aa0f4627e2362d775a321664e66 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/auth0
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@5a618720076d3aa0f4627e2362d775a321664e66 -
Trigger Event:
workflow_dispatch
-
Statement type:
File details
Details for the file auth0_fastapi-1.0.0b5-py3-none-any.whl.
File metadata
- Download URL: auth0_fastapi-1.0.0b5-py3-none-any.whl
- Upload date:
- Size: 32.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
dbe70a13a0623ba73719fca39550e666dae781ded5d3579f0f749cb8f3fad99b
|
|
| MD5 |
a601610eddb556e362c4ade6095e9b9c
|
|
| BLAKE2b-256 |
79868c9a40c939297ac98fa7ae17628e7c7a6d64d91d649b1af5ccbe7862a0f7
|
Provenance
The following attestation bundles were made for auth0_fastapi-1.0.0b5-py3-none-any.whl:
Publisher:
publish.yml on auth0/auth0-fastapi
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
auth0_fastapi-1.0.0b5-py3-none-any.whl -
Subject digest:
dbe70a13a0623ba73719fca39550e666dae781ded5d3579f0f749cb8f3fad99b - Sigstore transparency entry: 707643201
- Sigstore integration time:
-
Permalink:
auth0/auth0-fastapi@5a618720076d3aa0f4627e2362d775a321664e66 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/auth0
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@5a618720076d3aa0f4627e2362d775a321664e66 -
Trigger Event:
workflow_dispatch
-
Statement type: