Search code examples
djangodjango-rest-frameworkdjango-middleware

Calling a custom middleware after Authentication Middleware


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


Solution

  • 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.