django-casbin icon indicating copy to clipboard operation
django-casbin copied to clipboard

In DRF, Middleware which uses request.user is always Anonymous

Open zhiming429438709 opened this issue 2 years ago • 3 comments

In DRF, Middleware which uses request.user is always Anonymous, but in view, the user is not anonymous

zhiming429438709 avatar Sep 22 '22 06:09 zhiming429438709

@techoner @Nekotoxin

casbin-bot avatar Sep 22 '22 06:09 casbin-bot

hello, what is "DRF"?

Nekotoxin avatar Sep 22 '22 06:09 Nekotoxin

@Nekotoxin @zhiming429438709 I think it's https://www.django-rest-framework.org/ ?

hsluoyz avatar Sep 22 '22 13:09 hsluoyz

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

ziranl16 avatar Dec 16 '22 07:12 ziranl16

Closed as resolved

hsluoyz avatar Dec 31 '22 07:12 hsluoyz