Django Rest Framework authentication and Django Middleware: Why request.user is anonymous?

When using DRF and in in the context of Django middleware I have often found to be the case that request.user is an AnonymousUser. Why is that?

It is because the DRF authentication classes are executed after all the normal Django middleware are already in their get_response stage.

If you want to setup a logger enriched with user meta data it doesn’t not make sense to wait for the response from DRF to setup things properly… So what can you do to fix that?

A simple way to hook into DRF auth system is to subclass the authentication mechanism that you use. For example let’s say you are using Django REST Framework Simple JWT plugin you can subclass it this way:

Then substitute the old authentication class with your own

You should now be able to use the request_context ContextVar within DRF. For example you could use it in a special logger or have a DRF Serializer that takes advantages of the user language to return a specific translations. Here is an example on how to use it:

And voilà! that should work.

--

--

I am me!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store