TCatshoek / fastapi-nextauth-jwt

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

Exceptions are not handled by FastAPI #10

Closed b0n3sh closed 1 month ago

b0n3sh commented 2 months ago

Hello,

Thanks for this implementation, it allows to connect my API with NextJS.

I realized, than if the user is missing the actual cookie, the server just yields a 500 internal error message, cause fastapi-nextauth-jwt is just raising an standard Exception.

raise MissingTokenError(status_code=401, message=f"Missing cookie: {cookie_name}")
fastapi_nextauth_jwt.exceptions.MissingTokenError
INFO:     127.0.0.1:53022 - "GET / HTTP/1.1" 500 Internal Server Error

I expected to receive a 401 unauthorized message error (as the library seems to be trying to do). I replaced locally the Exceptions with the FastAPI HTTPException and seems to be working now good.

I don't know if it was made otherwise with other scenario in mind.

In any case, I forked the project so you can see exactly what I changed.

Thanks again for this project.

TCatshoek commented 1 month ago

Hi b0n3sh,

Sorry for the late response, I hadn't looked on here in a while.

I think the way I would do this is add a custom exception handler in fastapi.

Something like (untested):

@app.exception_handler(NextAuthJWTException)
async def unicorn_exception_handler(request: Request, exc: NextAuthJWTException):
    return JSONResponse(
        status_code=401,
        content={"message": "Unauthorized"},
    )

Depending on how much info you want to send to the client, you could also forward the status code and message from the exception.

b0n3sh commented 1 month ago

How silly of me, I didn't know about that way of creating custom handlers. Thanks, it works better this way (:

TCatshoek commented 1 month ago

No worries, glad I could help!