django-casbin
django-casbin copied to clipboard
In DRF, Middleware which uses request.user is always Anonymous
In DRF, Middleware which uses request.user is always Anonymous, but in view, the user is not anonymous
@techoner @Nekotoxin
hello, what is "DRF"?
@Nekotoxin @zhiming429438709 I think it's https://www.django-rest-framework.org/ ?
Hi @zhiming429438709 @hsluoyz , I have spent some time debugging this issue and here are my findings and proposals.
To summarize, if we use DjangoRestFramework(DRF), then any custom middleware would only get Anonymous when calling request.user. This issue is mainly caused by DRF, and there are many active discussions in DRF community. Personally, I think that this issue is currently under heated discussion in the DRF community, and you can try to solve this by following the advice and suggestions from DRF community.
Main Cause: DRF overrides the default Django view code and executes its own. It wraps the original request with its own methods, and one of those methods is DRF authentication. The reason why DRF doesn't show user in middleware is that DRF sets user only when it processes views. So any other middleware won't be able to see requests.user as it only gets its value after view_middleware executes.
Proposed Solution:
DRF community has proposed some solutions, which I have referenced some in the reference list below.
The main idea of these popular solutions is to use SimpleLazyObject
to get the user from DRF token.
References: https://stackoverflow.com/questions/54171931/django-auth-self-request-user-is-always-anonymous-in-viewset https://github.com/jpadilla/django-rest-framework-jwt/issues/45 https://groups.google.com/g/django-rest-framework/c/YvWiNNCmk8o?pli=1 https://stackoverflow.com/questions/60846831/django-custom-middleware-request-user-always-anonymoususer
Closed as resolved