A fastapi dependency used to decode jwt tokens generated by nextauth,
Project description
fastapi-nextauth-jwt
This project provides a FastAPI dependency for decrypting and validating JWTs generated by Auth.js. It is designed to facilitate the integration of a FastAPI backend with Next.js and NextAuth/Auth.js on the frontend.
[!NOTE] Using Auth.js with frameworks other than Next.js may work but has not been tested
Features
- JWT Decryption & Validation: Seamlessly decrypt and validate JWTs generated by Auth.js
- CSRF Protection: Built-in Auth.js-compatible CSRF protection with configurable HTTP methods
- Flexible Configuration: Extensive customization options for encryption algorithms, cookie names, and security settings
- NextAuth.js v4 Compatibility: Includes a compatibility layer for NextAuth.js v4 through
NextAuthJWTv4
Installation
pip install fastapi-nextauth-jwt
Basic Usage
from typing import Annotated
from fastapi import FastAPI, Depends
from fastapi_nextauth_jwt import NextAuthJWT
app = FastAPI()
JWT = NextAuthJWT(
secret="y0uR_SuP3r_s3cr37_$3cr3t", # Leave this out to automatically read the AUTH_SECRET env var
)
@app.get("/")
async def return_jwt(jwt: Annotated[dict, Depends(JWT)]):
return jwt
Configuration Options
Essential Settings
- secret (str): The secret key used for JWT operations. Should match
AUTH_SECRETin your Next.js app. Leave this out to automatically read theAUTH_SECRETenvironment variable.JWT = NextAuthJWT(secret=os.getenv("YOUR_SECRET_ENV_VAR_NAME")))
Additional Options
If your auth.js settings are left at their defaults, you shouldn't need to touch these.
Security Options
-
csrf_prevention_enabled (bool): Enable CSRF protection
- Defaults to
Falsein development (ENV=dev),Trueotherwise
- Defaults to
-
csrf_methods (Set[str]): HTTP methods requiring CSRF protection
- Default:
{'POST', 'PUT', 'PATCH', 'DELETE'}
- Default:
Cookie Configuration
-
secure_cookie (bool): Enable secure cookie attributes
- Default:
True(whenAUTH_URLstarts with https)
- Default:
-
cookie_name (str): Session token cookie name
- Default:
"__Secure-authjs.session-token"(when secure_cookie is True) - Default:
"authjs.session-token"(when secure_cookie is False)
- Default:
-
csrf_cookie_name (str): CSRF token cookie name
- Default:
"__Host-authjs.csrf-token"(when secure_cookie is True) - Default:
"authjs.csrf-token"(when secure_cookie is False)
- Default:
[!TIP] If you're using the latest version of Auth.js, here's the recommended configuration:
JWT = NextAuthJWT( secret=os.environ["AUTH_SECRET"], )
Advanced Options
-
encryption_algorithm (str): JWT encryption algorithm
- Supported:
"A256CBC-HS512"(default),"A256GCM"
- Supported:
-
check_expiry (bool): Enable JWT expiration validation
- Default:
True
- Default:
NextAuth.js v4 Compatibility
For NextAuth.js v4 applications, use the NextAuthJWTv4 class:
from fastapi_nextauth_jwt import NextAuthJWTv4
JWT = NextAuthJWTv4(
secret=os.getenv("AUTH_SECRET")
)
This provides compatibility with the v4 token format and default settings
Best Practices
-
Environment Variables: Always use environment variables for sensitive values:
JWT = NextAuthJWT( secret=os.getenv("AUTH_SECRET"), )
-
HTTPS in Production: Ensure
AUTH_URLstarts withhttps://in production to enable secure cookies -
CSRF Protection: Keep CSRF protection enabled in production environments
Examples
A simple example is available in the examples folder. It demonstrates:
- Using Next.js URL rewrites to route requests to FastAPI
- Basic JWT validation setup
- CSRF protection configuration
You can also place both the backend and frontend behind a reverse proxy like nginx, as long as the auth.js cookies reach FastAPI.
Environment Variables
AUTH_SECRET: The secret key used for JWT operations (required)AUTH_URL: The URL of your application (affects secure cookie settings)ENV: Set to"dev"to disable CSRF protection in development
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 fastapi_nextauth_jwt-2.1.1.tar.gz.
File metadata
- Download URL: fastapi_nextauth_jwt-2.1.1.tar.gz
- Upload date:
- Size: 69.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
97d24df96661c78a4c7003f78459cc6df36eccd77656a3067628cace34863754
|
|
| MD5 |
169e26ee77e9621c16c51d26952891c8
|
|
| BLAKE2b-256 |
b1e3f569b861a78c92c1ba1a8abb450db757feb2d1e0f499cc44a558492ce473
|
Provenance
The following attestation bundles were made for fastapi_nextauth_jwt-2.1.1.tar.gz:
Publisher:
publish.yml on TCatshoek/fastapi-nextauth-jwt
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
fastapi_nextauth_jwt-2.1.1.tar.gz -
Subject digest:
97d24df96661c78a4c7003f78459cc6df36eccd77656a3067628cace34863754 - Sigstore transparency entry: 219601630
- Sigstore integration time:
-
Permalink:
TCatshoek/fastapi-nextauth-jwt@e35be99689bdbc94bf9bfff00cb1763f2e6aa48c -
Branch / Tag:
refs/heads/main - Owner: https://github.com/TCatshoek
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@e35be99689bdbc94bf9bfff00cb1763f2e6aa48c -
Trigger Event:
workflow_dispatch
-
Statement type:
File details
Details for the file fastapi_nextauth_jwt-2.1.1-py2.py3-none-any.whl.
File metadata
- Download URL: fastapi_nextauth_jwt-2.1.1-py2.py3-none-any.whl
- Upload date:
- Size: 8.7 kB
- Tags: Python 2, Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
2beb72fa7124e857c79204c4828ed50e783933f8a7c0bf51ac65f20806dc44df
|
|
| MD5 |
847cc23504a3b1ac96cd20fd0e5fdc81
|
|
| BLAKE2b-256 |
020f77402cfd8791af1bd7ff8fcadf8b56c13aa83253201a5e3157b13c6d0faa
|
Provenance
The following attestation bundles were made for fastapi_nextauth_jwt-2.1.1-py2.py3-none-any.whl:
Publisher:
publish.yml on TCatshoek/fastapi-nextauth-jwt
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
fastapi_nextauth_jwt-2.1.1-py2.py3-none-any.whl -
Subject digest:
2beb72fa7124e857c79204c4828ed50e783933f8a7c0bf51ac65f20806dc44df - Sigstore transparency entry: 219601631
- Sigstore integration time:
-
Permalink:
TCatshoek/fastapi-nextauth-jwt@e35be99689bdbc94bf9bfff00cb1763f2e6aa48c -
Branch / Tag:
refs/heads/main - Owner: https://github.com/TCatshoek
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@e35be99689bdbc94bf9bfff00cb1763f2e6aa48c -
Trigger Event:
workflow_dispatch
-
Statement type: