Home:ALL Converter>Cannot use User in Django Rest Framework Custom Request middleware using JWT token after created new middleware

Cannot use User in Django Rest Framework Custom Request middleware using JWT token after created new middleware

Ask Time:2019-11-30T16:42:40         Author:Yery cs

Json Formatter

I want to use request.user in Django Rest Framework custom middleware. It returns AnnonymousUser and I failed.

I created new Custom middleware which returns real user.

from django.contrib.auth.middleware import get_user
from django.utils.functional import SimpleLazyObject
from rest_framework_jwt.authentication import JSONWebTokenAuthentication

class AuthenticationMiddlewareJWT(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        request.user = SimpleLazyObject(lambda: self.__class__.get_jwt_user(request))
        return self.get_response(request)

    @staticmethod
    def get_jwt_user(request):
        user = get_user(request)
        if user.is_authenticated:
            return user
        jwt_authentication = JSONWebTokenAuthentication()
        if jwt_authentication.get_jwt_value(request):
            user, jwt = jwt_authentication.authenticate(request)
        return user

Above middleware, jwt_authentication.get_jwt_value(request), this returns always None.

How can I fix it and use request.user in custom middleware?

Author:Yery cs,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/59114575/cannot-use-user-in-django-rest-framework-custom-request-middleware-using-jwt-tok
yy