Skip to content
This repository has been archived by the owner on Sep 13, 2023. It is now read-only.

Right way to add authentification middleware #692

Open
aguschin opened this issue Jul 11, 2023 · 0 comments
Open

Right way to add authentification middleware #692

aguschin opened this issue Jul 11, 2023 · 0 comments
Labels
enhancement New feature or request feedback User's feedback plugins Plugins and extensions for MLEM! serve Serving models

Comments

@aguschin
Copy link
Contributor

Adding middleware ended up dirtier than if I wrote the code for FastAPI serving myself, because the FastAPIMiddleware seems to be applied after the serializer, and I wanted a middleware applied before serializers (for authentication purposes).

Other question:
If I'm understanding correctly, the middleware on_request methods are called after the request_serializer. Is there a way to add layers before the request_serializer.

I was trying to add authentification middleware (for FastApi). I first tried to inherit from FastAPIMiddleware , and do a test in the on_request method (to test if the field api_key of the request header has the correct value). The problem is, since I am using the pil_numpy serializer, the request argument of on_request is a Numpy array.

So the only solution I have found is:

class KeyAuthMiddleware(FastAPIMiddleware):
    api_key: str

    def on_app_init(self, app: FastAPI):
        @app.middleware("http")
        async def api_key_auth_middleware(request: Request, call_next):
            api_key = request.headers.get("api_key")
            if api_key != self.api_key:
                raise HTTPException(status_code=401, detail="Invalid API Key")
            response = await call_next(request)
            return response

Is there a better way to do it?

reported in discord

@aguschin aguschin added enhancement New feature or request plugins Plugins and extensions for MLEM! feedback User's feedback serve Serving models labels Jul 11, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
enhancement New feature or request feedback User's feedback plugins Plugins and extensions for MLEM! serve Serving models
Projects
None yet
Development

No branches or pull requests

1 participant