Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 213
anubysh Avatar asked Nov 09 '18 13:11

anubysh


People also ask

Is authentication a middleware?

In this route, passport. authenticate() is middleware which will authenticate the request. By default, when authentication succeeds, the req. user property is set to the authenticated user, a login session is established, and the next function in the stack is called.

What is middleware What is important how do you write custom Middlewares in Django?

Middleware is a framework of hooks into Django's request/response processing. It's a light, low-level “plugin” system for globally altering Django's input or output. Each middleware component is responsible for doing some specific function.


1 Answers

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.

like image 77
Atul Mishra Avatar answered Oct 03 '22 23:10

Atul Mishra