2

I`m using the django remote user middleware, and an own middleware mysupermiddleware:

MIDDLEWARE = [    
    ...,
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.RemoteUserMiddleware',
    'my_project.middleware.mysupermiddleware',
]

When a remote user authenticates, it is available in the view. request.user shows the username.

But in my middleware, it is not available

def mysupermiddleware(get_response):

    def middleware(request):
        print (request.user)

request.user returns AnonymousUser

When I print request.user in my view, it returns the remote authenticated user.

When I authenticate with ModelBackend instead RemoteUserBackend, the user is available in middleware and view.

Is this intended? How do I make the remote user available in the middleware? Django version is 3.1.1

EDIT: Found the reason: It is related to rest framework authentication: At this stackoverflow post the user @imposeren states, that

if you are using something other than rest_framework.authentication.SessionAuthentication as an authentication_class, then request.user is set outside of middlewares (somewhere during View.dispatch)

Does somebody have an idea, on how to use user in middleware regardless?

user1383029
  • 1,685
  • 2
  • 19
  • 37
  • Try reordering the middleware in the list? – AKX Jan 06 '21 at 10:04
  • Yes: When I set it before `AuthenticationMiddleware`, request.user is not defined. When I set if between `AuthenticationMiddleware` and `RemoteUserMiddleware`, then is is anonymous, too... – user1383029 Jan 06 '21 at 10:57
  • Ok, found the answer, is a duplicate of this post: https://stackoverflow.com/questions/50793212/django-jwt-authentication-user-is-anonymous-in-middleware/65594951 Maybe a mod can mark this as duplicate – user1383029 Jan 06 '21 at 11:30

0 Answers0