Django and Middleware which uses request.user is always Anonymous

前端 未结 7 1192
天命终不由人
天命终不由人 2021-01-30 10:37

I\'m trying to make middleware which alters some fields for the user based on subdomain, etc...

The only problem is the request.user always comes in as AnonymousUser wit

7条回答
  •  执笔经年
    2021-01-30 11:37

    I wasn't quite happy with the solutions out there. Here's a solution that uses some DRF internals to make sure that the correct authentication is applied in the middleware, even if the view has specific permissions classes. It uses the middleware hook process_view which gives us access to the view we're about to hit:

    class CustomTenantMiddleware():
        def process_view(self, request, view_func, view_args, view_kwargs):
            # DRF saves the class of the view function as the .cls property
            view_class = view_func.cls
            try:
                # We need to instantiate the class
                view = view_class()
                # And give it an action_map. It's not relevant for us, but otherwise it errors.
                view.action_map = {}
                # Here's our fully formed and authenticated (or not, depending on credentials) request
                request = view.initialize_request(request)
            except (AttributeError, TypeError):
                # Can't initialize the request from this view. Fallback to using default permission classes
                request = APIView().initialize_request(request)
    
            # Here the request is fully formed, with the correct permissions depending on the view.
    

    Note that this doesn't avoid having to authenticate twice. DRF will still happily authenticate right afterwards.

提交回复
热议问题