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

Alasdair
  • 298,606
  • 55
  • 578
  • 516
anubysh
  • 576
  • 6
  • 18
  • i meant custom middleware – anubysh Nov 09 '18 at 14:52
  • 1
    Please show the `UserMiddleware`. Since you are using Rest Framework, perhaps that code should go somewhere else, e.g. [an authentication class](https://www.django-rest-framework.org/api-guide/authentication/#how-authentication-is-determined). – Alasdair Nov 09 '18 at 15:08
  • Look on [this question](https://stackoverflow.com/questions/26240832/django-and-middleware-which-uses-request-user-is-always-anonymous). It helped me to solve similar problem – rborodinov May 13 '21 at 12:39

1 Answers1

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.

Atul Mishra
  • 1,898
  • 2
  • 13
  • 18