0

I am trying to log all my FastAPI requests (who requested, what and what is the status code) by creating a custom APIRoute-class. This is my custom Route-class:

class LoggingRoute(APIRoute):
    def get_route_handler(self) -> Callable:
        original_route_handler = super().get_route_handler()

        async def custom_route_handler(request: Request) -> Response:
            response: Response = await original_route_handler(request)
            log_request(
                user = request.user,
                url = request.url,
                method = request.method,
                status_code = response.status_code
            )
            return response

        return custom_route_handler

The logging would work if we don't want to include request.user to the logs. When trying to access the user, the following error is thrown:

AssertionError: AuthenticationMiddleware must be installed to access request.user

I guess the user-attribute of the request is not yet initialized inside the route handler. request.user works well when handling the request later.

My question is: is there any way for me to get access to request.user inside the custom_route_handler-function? If not, is there another way to implement the logging functionality with ability to log the user as well?

juhat
  • 342
  • 2
  • 10
  • In what order do you register the middlewares? – MatsLindh Oct 18 '22 at 07:55
  • @MatsLindh I followed this guide to setup the authentication: https://intility.github.io/fastapi-azure-auth/single-tenant/fastapi_configuration It seems that there's just the CORSMiddleware registered when starting the app. – juhat Oct 18 '22 at 09:55

1 Answers1

0

You must install AuthenticationMiddleware.

https://www.starlette.io/authentication/#users
Once AuthenticationMiddleware is installed the request.user interface will be available to endpoints or other middleware.

app = FastAPI(middleware=[Middleware(AuthenticationMiddleware)])
Jedore
  • 333
  • 3
  • 13