Search code examples
django-rest-frameworkjwttoken

How to know which user is assigned to the token (JWT Django rest framework)?


I am trying to make a blog update API view but I need to know if the user updating the post is the same as author of the blog the token is given in the headers like this "Authorization Bearer " how do I know if the header token's user is same as the author of the blog post?


Solution

  • Each JWT token has a payload and a signature. You can read more here. If you are using the package djangorestframework-simplejwt then the payload will be something like {"user_id": 1}. That's how you know which user it belongs to. (It's encoded in base64, so you would have to decode it to see this information).

    However, you don't really have to think about this since that package will parse the token for you. Therefore you can simply use request.user in your views to know which user is authenticated. And to check if it's the same as in Blog object, you can just do something like:

    blog = Blog.objects.get(pk=1)
    if request.user == blog.created_by:
        pass