Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get username in a middleware from Django Rest Framework SIMPLE JWT token (3rd party)

I am using Django Rest Framework and I've included a 3rd party package called REST framework simple JWT Auth which is the new framework referenced, and this one, REST framework JWT Auth, which is the old one (I Imagine), since there was no update on github since a long time and maybe not supported for newer versions.

And I'm looking for a way, like this link on stackoverflow-3rd answer, via middlewares, to get the user information for each request in order to apply/save it, in needed, the user object in my models by using django signals. I checked in documentation and on internet, but I didn't find anything. So, if you already had that case, I will appreciate your help.

Thank you

like image 617
Tounnbounn Avatar asked Dec 10 '22 03:12

Tounnbounn


2 Answers

To get username from the user model you should use request.user. This will give you the authenticated user's info with the request. However if you use simple_jwt, it's not possible to directly use request.user in a middleware because authentication mechanism works in view function.

So you should manually authenticate inside the middleware and then you can use request.user to get whatever data from the user model.

from rest_framework_simplejwt import authentication


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

    def __call__(self, request):
        response = self.get_response(request)
        return response

    def process_view(self, request, view_func, view_args, view_kwargs):
        request.user = authentication.JWTAuthentication().authenticate(request)[0]  # Manually authenticate the token

        print(request.user)  # Use the request.user as you want
like image 79
Mansur Avatar answered May 16 '23 07:05

Mansur


With simple_jwt the user information will not be set on the request initially but after the request is processed it will be. So if you're just logging the information and you can do it after the request is processed, do it there.

So for example in a simple middleware:

def simple_middleware(get_response):
    def middleware(request):
        # request.user is an anonymous user at this point
        response = get_response(request)
        # request.uesr is the logged-in user here
        return response
    return middleware
like image 45
Greg Butler Avatar answered May 16 '23 09:05

Greg Butler