A fastapi dependency used to decode jwt tokens generated by nextauth,
Project description
fastapi-nextauth-jwt
This project contains a FastAPI dependency that can be used to decrypt and validate JWTs generated by Auth.js. The purpose of this project is to make it easy to use a FastAPI backend in projects that use Next.js and NextAuth / Auth.js in the frontend. It might work with other frameworks using Auth.js too! (But I haven't tested that, feel free to contribute if you do)
Besides JWT decryption and validation, Auth.js compatible cross-site request forgery (CSRF) protection is also implemented.
Installation
pip install fastapi-nextauth-jwt
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",
)
@app.get("/")
async def return_jwt(jwt: Annotated[dict, Depends(JWT)]):
return jwt
There are a few configuration options available in the NextAuthJWT constructor, but the most important one is secret
,
which should be equivalent to NEXTAUTH_SECRET
on the Next.js side. Please don't hardcode the secret like this in a real application,
but rely on the NEXTAUTH_SECRET
env var :)
It is also possible to enable or disable CSRF protection using csrf_prevention_enabled
.
If this is not set, this will looks at the ENV environment variable. If this is dev
then CSRF protection will be disabled.
It is also possible to customize the HTTP verbs to which CSRF protection is applied.
You should also set the NEXTAUTH_URL
environment variable, as it is used to determine
whether secure cookies are being used. Or you can set the cookie names manually.
NextAuth / Auth.js v4 compatibility
A compatibility shim is included if you're still on NextAuth v4, just replace NexAuthJWT
with NextAuthJWTv4
Examples
A simple example is available in the examples folder. It uses Next.js URL rewrites to direct requests to FastAPI. This is just one way to do it, putting both the backend and frontend behind something like nginx would also be a good strategy. As long as the cookies can make it to FastAPI you should be good to go!
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
Hashes for fastapi_nextauth_jwt-2.0.0.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | 25e1f1fe7506da29156bb4db4c29d0af537f788a77867e2be3a8d1f65340da1d |
|
MD5 | 1df7175a93ee16783641bd6296f068eb |
|
BLAKE2b-256 | c2d4e25df09d71fa1453ee0daa6e29d6b595e9a870f2c65df23bd26c5c353abe |
Hashes for fastapi_nextauth_jwt-2.0.0-py2.py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | ce2d758b8e2d4ff4d770216d15911c01a9f8878d2313beafbd340fcfeb9ffdff |
|
MD5 | 022ca1684d0ad67e7c7521dea5ee365e |
|
BLAKE2b-256 | 8f2641e231e058940a209f61e6b2b1fdb20b41df97325a6a408de62a2690e0a2 |