Django and Middleware which uses request.user is always Anonymous

前端 未结 7 1195
天命终不由人
天命终不由人 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:30

    Daniel Dubovski's solution is probably the best in most cases.

    The problem with the lazy object approach is if you need to rely on the side effects. In my case, I need something to happen for each request, no matter what.

    If I'd use a special value like request.custom_prop, it has to be evaluated for each request for the side effects to happen. I noticed that other people are setting request.user, but it doesn't work for me since some middleware or authentication class overwrites this property.

    What if DRF supported its own middleware? Where could I plug it in? The easiest way in my case (I don't need to access the request object, only the authenticated user) seems to be to hook into the authentication class itself:

    from rest_framework.authentication import TokenAuthentication
    
    class TokenAuthenticationWithSideffects(TokenAuthentication):
    
        def authenticate(self, request):
            user_auth_tuple = super().authenticate(request)
    
            if user_auth_tuple is None:
                return
            (user, token) = user_auth_tuple
    
            # Do stuff with the user here!
    
            return (user, token)
    

    Then I could just replace this line in my settings:

    REST_FRAMEWORK = {
        "DEFAULT_AUTHENTICATION_CLASSES": (
            #"rest_framework.authentication.TokenAuthentication",
            "my_project.authentication.TokenAuthenticationWithSideffects",
        ),
        # ...
    }
    

    I'm not promoting this solution, but maybe it will help someone else.

    Pros:

    • It to solves this specific problem
    • There's no double authentication
    • Easy to maintain

    Cons:

    • Not tested in production
    • Things happen in an unexpected place
    • Side effects...

提交回复
热议问题