TCatshoek / fastapi-nextauth-jwt

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

Invalid JWT format #7

Closed CyrusVorwald closed 10 months ago

CyrusVorwald commented 11 months ago

Using NextAuth with Google login, I get this error:

jose.exceptions.JWEParseError: Not enough segments

With this script, NEXTAUTH_SECRET removed:

import os

os.environ['NEXTAUTH_URL'] = os.environ.get('NEXTAUTH_URL', "http://localhost:3000") os.environ['NEXTAUTH_SECRET'] = os.environ.get('NEXTAUTH_SECRET', "")

from typing import Annotated from fastapi import Depends, FastAPI

from fastapi_nextauth_jwt import NextAuthJWT

JWT = NextAuthJWT()

app = FastAPI()

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

CyrusVorwald commented 11 months ago

I was able to resolve this issue by passing into the auth.js api the session: { strategy: "jwt" } option. The code looks like this:

import NextAuth, { NextAuthOptions } from "next-auth"; import GoogleProvider from "next-auth/providers/google"; import { PrismaAdapter } from "@next-auth/prisma-adapter"; import prisma from "../../../lib/prismadb";

export const authOptions: NextAuthOptions = { adapter: PrismaAdapter(prisma), session: { strategy: "jwt" }, providers: [ GoogleProvider({ clientId: process.env.GOOGLE_CLIENT_ID || "", clientSecret: process.env.GOOGLE_CLIENT_SECRET || "", }), ], };

export default NextAuth({ ...authOptions, });

I am not entirely sure why this is the case because it says the default strategy is JWT here: https://next-auth.js.org/configuration/options#session

TCatshoek commented 10 months ago

Maybe setting an adapter changes the strategy to database automatically. From reading the docs, the session cookie then contains a session token, not sure if that's stored in a way that's a valid JWE. I'm very short on time currently but I'll look into it!

TCatshoek commented 10 months ago

@CyrusVorwald I finally had time to check, sorry for the wait. It seems that by default, nextauth indeed only stores a session identifier in the session token when using a database adapter, which is not a valid JWT and so can't be decoded as one.

CyrusVorwald commented 10 months ago

Thanks for double checking