0

These are the files which I'm using in my project

main.py

from fastapi import Depends, FastAPI
from mysqlx import Session

from database import test_db_connection
from utils import get_db, login_user
from schemas import UserLogin
from fastapi.security import OAuth2PasswordRequestForm

from routers import auth, candidates
from middlewares.auth import auth_middleware

app = FastAPI()

# Apply the auth_middleware to the /users endpoint
# app.include_router(users.router, prefix="/users", tags=["users"], dependencies=[Depends(auth_middleware)])

# Exclude the auth_middleware from the /login and /logout endpoints
# app.include_router(auth.router, prefix="/auth", tags=["auth"])

#include auth router
app.include_router(auth.auth_router, prefix="/auth")
app.include_router(candidates.candidate_router, prefix="/candidate")

# add auth middleware
app.add_middleware(auth_middleware)

Middlware is in middlewares/auth.py

from fastapi import HTTPException, Request
from fastapi.responses import JSONResponse
from typing import List
from starlette.status import HTTP_401_UNAUTHORIZED
import jwt, os
from jwt import PyJWTError

from utils import get_db
from models import User

async def auth_middleware(request: Request, call_next):
    excluded_routes = ['/login', '/logout']  # Add any routes that should be excluded
    path = request.url.path
    if path in excluded_routes:
        response = await call_next(request)
        return response
    token = request.headers.get('Authorization')
    # return 'dfsdf'
    if not token:
        return JSONResponse(status_code=HTTP_401_UNAUTHORIZED, content={'detail': 'Not authenticated'})
    # authentication logic
    try:
        decoded_token = jwt.decode(token, os.environ["SECRET_KEY"], algorithms=["HS256"])
        user = get_db().query(User).get(decoded_token["sub"])
        if user:
            request.state.current_user = user
        else:
            raise HTTPException(status_code=401, detail="Invalid authentication credentials")
    except PyJWTError:
        raise HTTPException(status_code=401, detail="Invalid authentication credentials")
    response = await call_next(request)
    return response

And when executing this using uvicorn main:app --reload This returns

INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [23456] using WatchFiles
INFO:     Started server process [23458]
INFO:     Waiting for application startup.
INFO:     ASGI 'lifespan' protocol appears unsupported.
INFO:     Application startup complete.

auth_middleware() function that I'm using. When I comment out this function, the APIs work without any issues, which suggests that the middleware is causing the internal server error. Can someone please help me to fix this as I'm very new to python and fastAPI

  • What version of FastAPI are you using? ASGI lifespan is only supported since version 0.93.0 – Simon May 04 '23 at 09:27

0 Answers0