0

I try to add the business attribute to the request object by using my own middleware, it nicely works with rest_framework.authentication.SessionAuthentication and I can use request.business in my views. But when I try to authenticate with JWT method (rest_framework_simplejwt.authentication.JWTAuthentication) when my middleware code is run request.user is set to AnonymouseUser so can't fetch business associated with user? Why did this happen?

# middleware.py

class MyMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        request.business = None

        if request.user.is_authenticated and hasattr(request.user, 'business'):
            request.business = request.user.business

        response = self.get_response(request)

        return response

Middlewares:

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',
    'my_app.middleware.MyMiddleware',
]

rest_framework settings:

REST_FRAMEWORK = {
    ...
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ],
}
Majid Rouhi
  • 78
  • 1
  • 10
  • Can you show your list of middlewares to see how they are ordered? – Charnel Mar 23 '21 at 10:07
  • Does this answer your question? [Django and Middleware which uses request.user is always Anonymous](https://stackoverflow.com/questions/26240832/django-and-middleware-which-uses-request-user-is-always-anonymous) – Abdul Aziz Barkat Mar 23 '21 at 10:12

1 Answers1

2

Unfortunately, DEFAULT_AUTHENTICATION_CLASSES are not processed in middleware process, but in the view itself. What is giving you the proper user when using session is the Django's AuthenticationMiddleware and REST Framework is just using this value when the session authentication is enabled.

To solve that, you can do one of the following:

  • Move adding request.business to the views (for example by adding some class that all your views will inherit from)
  • Move JWT authentication into Django middlewares (this has a side effect of DRF enforcing CSRF checks by default when user is logged in)
GwynBleidD
  • 20,081
  • 5
  • 46
  • 77