Django and Middleware which uses request.user is always Anonymous

前端 未结 7 1211
天命终不由人
天命终不由人 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-30 11:43

    I've solved this problem by getting DRF token from the requests and loading request.user to the user associated to that model.

    I had the default django authentication and session middleware, but it seems DRF was using it's token auth after middleware to resolve the user (All requests were CORS requests, this might have been why). Here's my updated middleware class:

    from re import sub
    from rest_framework.authtoken.models import Token
    from core.models import OrganizationRole, Organization, User
    
    class OrganizationMiddleware(object):
    
      def process_view(self, request, view_func, view_args, view_kwargs):
        header_token = request.META.get('HTTP_AUTHORIZATION', None)
        if header_token is not None:
          try:
            token = sub('Token ', '', request.META.get('HTTP_AUTHORIZATION', None))
            token_obj = Token.objects.get(key = token)
            request.user = token_obj.user
          except Token.DoesNotExist:
            pass
        #This is now the correct user
        print (request.user)
    

    This can be used on process_view or process_request as well.

    Hopefully this can help someone out in the future.

提交回复
热议问题