TCatshoek / fastapi-nextauth-jwt

FastAPI Dependency to decode nextauth generated JWTs, for use in projects that mix nextjs/nextauth and fastapi.
MIT License
119 stars 9 forks source link

Missing Token Error: #14

Open JaydenCS opened 2 days ago

JaydenCS commented 2 days ago

Was just setting up and testing using the following code


from typing import Annotated
from fastapi import FastAPI, Depends
from fastapi_nextauth_jwt import NextAuthJWT
from fastapi.middleware.cors import CORSMiddleware
import os

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

JWT = NextAuthJWT(
    secret=os.getenv("NEXTAUTH_SECRET"),
    secure_cookie=False,
)

from fastapi import Request

@app.middleware("http")
async def log_request(request: Request, call_next):
    print("Cookies:", request.cookies)
    response = await call_next(request)
    return response

@app.get("/")
async def return_jwt(jwt: Annotated[dict, Depends(JWT)]):
    return {"message": f"Hi {jwt['name']}. Greetings from fastapi!"}

# For CSRF protection testing
@app.post("/")
async def return_jwt(jwt: Annotated[dict, Depends(JWT)]):
    return {"message": f"Hi {jwt['name']}. Greetings from fastapi!"}

The Error:

Screenshot from 2024-12-03 22-17-30

TCatshoek commented 1 day ago

Looks like your request does not have the cookie attached that contains the JWT, how are you making the request?

JaydenCS commented 1 day ago

Just like you said in the document:

Here is the code:


const FastAPITest = async () => {
    try {
      const csrfToken = await getCsrfToken();
      console.log(csrfToken);
      const response = await fetch("http://localhost:8000/", {
        method: "POST",
        headers: {
          "X-XSRF-Token": csrfToken,
        },
        credentials: "include",
      });

      if (!response.ok) {
        throw new Error("Network response was not ok");
      }

      console.log(response.json);
    } catch (error) {
      console.error("Error making authenticated request:", error);
      throw error;
    }