Calling a custom middleware after Authentication Middleware
Asked Answered
P

1

9

In django REST framework authentication middleware sets the user object in request ONLY after the views middleware is executed while any custom middleware is executed before that. is there someway to change this order and execute custom middleware AFTER user object is set by authentication middleware

As an alternative I create the user object in the middleware itself and it works fine but this is just a hack.

The middlewares as defined in common.py are:

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    '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',
    'application.middlewares.IPsBlockerMiddlewareHook',
    'application.middlewares.UserMiddleware',
]

The custom middleware in question is UserMiddleware. I need it to be executed after authentication but doesnt seems to be the case

Provost answered 9/11, 2018 at 13:32 Comment(3)
i meant custom middlewareProvost
Please show the UserMiddleware. Since you are using Rest Framework, perhaps that code should go somewhere else, e.g. an authentication class.Standush
Look on this question. It helped me to solve similar problemAbsent
C
4

Middlewares are executed in the top to bottom order when the request comes and in bottom to top when the response is sent. You can specify your custom middleware after the authentication middleware and it will run after that.

Cancroid answered 13/10, 2019 at 6:53 Comment(1)
It's about DRF authentication and middleware. In DRF, we just configure authentication backend. The problem is request.user is always Annonymous in custom middelwares in DRF.Rolandrolanda

© 2022 - 2024 — McMap. All rights reserved.