Skip to main content

A fastapi dependency used to decode jwt tokens generated by nextauth,

Project description

fastapi-nextauth-jwt

PyPI version

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


Download files

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

Source Distribution

fastapi_nextauth_jwt-2.0.0.tar.gz (68.3 kB view hashes)

Uploaded Source

Built Distribution

fastapi_nextauth_jwt-2.0.0-py2.py3-none-any.whl (7.8 kB view hashes)

Uploaded Python 2 Python 3

Supported by

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