AnonymousUser in DjangoRestFramework Middleware

3,412 views
Skip to first unread message

Yery cs

unread,
Nov 30, 2019, 2:06:46 PM11/30/19
to Django REST framework
Hello, How are you?

I am suck with Django Rest framework issue.

I am trying to use `request.user` in Django Rest Framework middleware.

It returns AnonymousUser and I failed.

I have searched and searched but there is no answer.

I wonder if this is Django Rest framework issue.

Who faced this issue? And did you solve?

Thank you.

Oleg Nykolyn

unread,
Nov 30, 2019, 2:50:24 PM11/30/19
to django-res...@googlegroups.com
Hi,

Does this happen during real requests or in test-cases ?
For real HTTP request custom middleware might be the answer, please check https://github.com/GetBlimp/django-rest-framework-jwt/issues/45
Such middleware should override "request.user" using REST_FRAMEWORK.DEFAULT_AUTHENTICATION_CLASSES and be put in config file before other middleware which user request.user.

Test-cases might require "force_login()" instead of "force_authenticate()" for request.user to work in middleware.


--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-rest-framework/4c08081d-0706-4b70-b252-63f8ca8f7d17%40googlegroups.com.

Wanderley S

unread,
Nov 30, 2019, 3:01:30 PM11/30/19
to django-res...@googlegroups.com
Hi there's no issue there.
Let me explain some basics 

In "pure" Django a cookie called "csrftoken" is the responsible to control authentication and sessions. Hence, for all request Django receives this cookie is sent.

When building REST Api's you are not supposed to have any state at server side, therefore no sessions and this is a concept for RESTfull itself.

In order to have authentication in Django Rest, you should implement any type of token authentication. After that from all request from client you will attach the token in the header. The backend will receive this token and from it you will have the user.

Depending on your architecture, you can rely on cookie and send the csrf_token in your header aswell.

Enough with the basics, take a look at JWT (jason web tokens)

Also see the documentation at Django Rest Framework page, regarding authentication.

Sorry if I can't be more especific and give you snippets, but reading the docs and understanding this concepts are the initial point.
 My suggestion is that you try to implement and use Django Rest framework jwt

Hope helped in anyway.



--

Yery cs

unread,
Nov 30, 2019, 3:04:16 PM11/30/19
to Django REST framework
Hello, Thanks for your reply.
I have already checked this github comments.
I added custom middleware in settings middlewares after Authentication middleware.
But I got still Anonymous user.
About test, can you explain about force_login?
About project status, I am printing logs in console like `print(request.user)` in middleware.
Console says `AnonymousUser`.
How can I fix it?
Thank you.

Wanderley S

unread,
Nov 30, 2019, 3:10:23 PM11/30/19
to django-res...@googlegroups.com
Questions: 
1 - have you created a login view to retrieve the token?

2- in your request, from client, are you sending the token returned above within the header?

The flow is:
1 - authenticate user
2 - get the token 
3 - send the token in header for every request 



--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.

Yery cs

unread,
Nov 30, 2019, 3:10:32 PM11/30/19
to django-res...@googlegroups.com
Hello, thanks for you reply.
Sorry for my poor post. I understand concepts of Django authentication.
I am using DRF jwt.
I have added my custom middleware after Authentication middleware in settings file.
And I am printing request.user in console like this `print(request.user)` in my custom middleware.
But I get still AnonymousUser.
Can you tell me why it is, and how can I fix it?
Thank you.



Message has been deleted

Yery cs

unread,
Nov 30, 2019, 3:14:36 PM11/30/19
to django-res...@googlegroups.com


On Sun, Dec 1, 2019 at 4:13 AM Yery cs <yeryc...@gmail.com> wrote:


project.zip

Yery cs

unread,
Nov 30, 2019, 3:19:47 PM11/30/19
to django-res...@googlegroups.com
This is my prepared project for testing. Of course not main project.
You can run on your local. You can migrate and loaddata users.json.
password: admin
You can test using postman.

You can see 'AnonymousUser' on your console.
I hope it can be fixed.
Thank you.

Wanderley S

unread,
Nov 30, 2019, 3:34:30 PM11/30/19
to django-res...@googlegroups.com
Nothing to be sorry about.
I'll take a look at your code later, since I'm on mobile now.

Can you show me the code where you make the request?

You're using curl or some javascript client?


--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.

Oleg Nykolyn

unread,
Nov 30, 2019, 3:40:14 PM11/30/19
to django-res...@googlegroups.com
Hi,

Here is custom middleware, which works for this case, also attached project with applied changes -  it now show "admin" instead of AnonymousUser.
Reason why DRF doesn't show user in middleware - DRF does not provide it's own middleware for this and sets user only when it processes views. So any other middleware won't be able to see requests.user, unless Django's middleware will set it (not DRF!), but this means cookie/session auth.
I've spent a few day on same issue once, it's unfortunate that DRF doesn't provide built-in middleware for this, but workaround is quite simple and reliable.
```

from rest_framework_jwt.authentication import JSONWebTokenAuthentication

from django.utils.functional import SimpleLazyObject



# Workaround simialr to https://github.com/GetBlimp/django-rest-framework-jwt/issues/45 # noqa

class AuthenticationTokenMiddleware:

    """Authentication middleware which return user from token."""


    def __init__(self, get_response):

        """Initializer."""

        self.get_response = get_response


    def __call__(self, request):

        """Response."""

        user = request.user

        request.user = SimpleLazyObject(lambda: self.get_token_user(request,

                                                                    user))

        return self.get_response(request)


    def get_token_user(self, request, user):

        """Return user from DRF token."""

        try:

            authenticator = JSONWebTokenAuthentication()

            return authenticator.authenticate(request)[0]

        except Exception:

            return user

```

project.zip

Yery cs

unread,
Nov 30, 2019, 3:48:10 PM11/30/19
to django-res...@googlegroups.com
Hello. thanks for your help.
Unfortunately, I still get AnonymousUser. 
Can you check once more again?

Yery cs

unread,
Nov 30, 2019, 3:50:27 PM11/30/19
to django-res...@googlegroups.com
Screenshot from 2019-12-01 04-49-39.png

Yery cs

unread,
Nov 30, 2019, 3:55:13 PM11/30/19
to django-res...@googlegroups.com
Screenshot from 2019-12-01 04-49-39.png

Oleg Nykolyn

unread,
Nov 30, 2019, 3:57:07 PM11/30/19
to django-res...@googlegroups.com
Hi,

I get following output:

[30/Nov/2019 20:53:35] "POST /api/test/ HTTP/1.1" 405 41

admin

None

***************

[30/Nov/2019 20:54:34] "GET /api/test/ HTTP/1.1" 200 18


Have you extracted code from archive attached to previous message ? It contains changes in middleware.py and settings.py - extra middleware is added there:

```

MIDDLEWARE = [

    'django.middleware.security.SecurityMiddleware',

    'django.contrib.sessions.middleware.SessionMiddleware',

    'django.middleware.common.CommonMiddleware',

    'django.middleware.csrf.CsrfViewMiddleware',

    'django.contrib.auth.middleware.AuthenticationMiddleware',

    'django.contrib.messages.middleware.MessageMiddleware',

    'django.middleware.clickjacking.XFrameOptionsMiddleware',

    'middleware.middleware.AuthenticationTokenMiddleware',

    'middleware.middleware.PermissionMiddleware'

]

```



Yery cs

unread,
Nov 30, 2019, 3:59:18 PM11/30/19
to django-res...@googlegroups.com
Yes. I have extracted from project you sent.
I have checked two files and all changes can be seen.

Oleg Nykolyn

unread,
Nov 30, 2019, 4:08:20 PM11/30/19
to django-res...@googlegroups.com
Last idea - could it possibly be that you set header in a different way ?
It's quite mysterious that same code work differently, so maybe reason is in client's request...
I use following command(https://httpie.org as http client):
```

http GET 127.0.0.1:8000/api/test/  Authorization:Bearer\ "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNTc1MTQ3MTkyLCJleHAiOjE1NzUxNDc0OTIsInVzZXJfaWQiOjEsIm9yaWdfaWF0IjoxNTc1MTQ3MTkyfQ.tCDJ3nwe3k5xImxwzePbGitPGV4b_3A1EaF0hkQxzhc"

```



Yery cs

unread,
Nov 30, 2019, 4:12:15 PM11/30/19
to django-res...@googlegroups.com
Is there any relation with python version?

Yery cs

unread,
Nov 30, 2019, 4:19:47 PM11/30/19
to django-res...@googlegroups.com
I use postman to test api.
Can you tell me how to test api for you?

Screenshot from 2019-12-01 05-18-53.png

Wanderley S

unread,
Nov 30, 2019, 7:28:43 PM11/30/19
to django-res...@googlegroups.com
Postman is good. But seems that you doing it wrong.
I believe shouldn't use Basic Auth.
You just on headers and set the JWT token.
For the token part that depends which token middleware you're using.

You should have an endpoint to send a post with the username and password that will return the token

Then for other endpoints you pass this token in headers.

Wanderley S

unread,
Nov 30, 2019, 7:30:11 PM11/30/19
to django-res...@googlegroups.com
Please send a screenshot with the headers

Em sáb, 30 de nov de 2019 18:19, Yery cs <yeryc...@gmail.com> escreveu:

Yery cs

unread,
Dec 1, 2019, 2:10:58 AM12/1/19
to django-res...@googlegroups.com
If I don't use request.user in middleware, all apis works well with basic authentication.
So I guess, it is not related with basic authentication.

Yery cs

unread,
Dec 1, 2019, 2:29:35 AM12/1/19
to django-res...@googlegroups.com
Screenshot from 2019-12-01 15-28-57.png

Wanderley S

unread,
Dec 1, 2019, 5:40:37 AM12/1/19
to django-res...@googlegroups.com
Can you post and share your project on github?

Yery cs

unread,
Dec 1, 2019, 5:42:36 AM12/1/19
to django-res...@googlegroups.com

Yery cs

unread,
Dec 1, 2019, 6:04:47 AM12/1/19
to django-res...@googlegroups.com

Wanderley S

unread,
Dec 1, 2019, 6:32:27 AM12/1/19
to django-res...@googlegroups.com
Great,

I'take a look at it and let you know.


Yery cs

unread,
Dec 1, 2019, 11:13:02 PM12/1/19
to django-res...@googlegroups.com
Hello, I have solved the problem.
Thank you for your interesting.
For Wanderley S and Oleg Nykolyn.
Regards!

On Sun, Dec 1, 2019 at 7:33 PM Yery cs <yeryc...@gmail.com> wrote:
Thank you.

rohit jaiswal

unread,
Dec 2, 2019, 3:29:33 AM12/2/19
to django-res...@googlegroups.com
Can you tell which authentication system you are using? If none or if you failed to authenticate then by default you will be getting an Anonymous user instance.

On Sun 1 Dec, 2019, 12:36 AM Yery cs, <yeryc...@gmail.com> wrote:
Hello, How are you?

I am suck with Django Rest framework issue.

I am trying to use `request.user` in Django Rest Framework middleware.

It returns AnonymousUser and I failed.

I have searched and searched but there is no answer.

I wonder if this is Django Rest framework issue.

Who faced this issue? And did you solve?

Thank you.

--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.

Yery cs

unread,
Dec 2, 2019, 3:36:05 AM12/2/19
to django-res...@googlegroups.com
I am using JSONWebTokenAuthentication.
Yes. I got AnonymousUser by default.
I have solved the problem. Thank you.

Reply all
Reply to author
Forward
0 new messages