[Python] Add auth to FastAPI via Middleware and include in OpenAPI

Discussão em 'Python' iniciado por Stack, Dezembro 16, 2024.

  1. Stack

    Stack Membro Participativo

    Basic goal: A means of authenticating most (but not all) routes in one place (a separate file), seamlessly so that I don't have to add code/documentation to every one of the routes in order to get auth or openapi to work.

    I would like to implement a basic Bearer Authorization in FastAPI, but do so in class-based middle-ware. I've done this successfully, but I have not seen how to do this in a way that OpenAPI is aware of it (ie. there's no way to set auth tokens in the docs)

    class AuthMiddleware:
    def __init__(self, settings):
    self.settings = settings

    async def __call__(self, request: Request, call_next):
    if self.is_protected_url(request.method, request.url.path):
    auth = request.headers.get("Authorization")
    scheme, data = (auth or " ").split(" ", 1)
    if scheme != "Bearer":
    return JSONResponse(None, 401, {"WWW-Authenticate": "Bearer"})
    if data != self.settings.auth_token:
    return JSONResponse(None, 401, {"WWW-Authenticate": "Bearer"})

    return await call_next(request)

    def is_protected_url(self, method, url):
    """ does what it does """


    In the main file:

    from path.to.auth import AuthMiddleware

    auth_middleware = AuthMiddleware(settings)
    app.middleware("http")(auth_middleware)


    There seem to some existing auth classes to use, but I can't figure out how to properly get them to work in a class-based Middleware that is in a separate file (Depends doesn't resolve).

    See


    Continue reading...

Compartilhe esta Página