2

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?

moshfiqrony
  • 4,303
  • 2
  • 20
  • 29
  • This already has an answer [here](https://stackoverflow.com/questions/39823363/how-to-get-username-from-django-rest-framework-jwt-token) Please take a look! – shreeraviadhikari Jun 08 '21 at 06:45

2 Answers2

2

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
Felix Eklöf
  • 3,253
  • 2
  • 10
  • 27
1

It depends on the token used. If it's a JWT you can easily decode it and check the claims. You should have a sub claim inside which will identify the user. It might contain the user ID, their email or some other piece of information which identifies the user.

When using JWTs you should remember to validate them. You can use the list on jwt.io to find a library which will help you implement JWT verification. Have a look also at a JWT best practices article I wrote, to learn about the pitfalls of using JWTs.

If your access token is an opaque token. Then you should be using Token introspection to get the data assigned to your token (The Server which issues tokens should expose a Token Introspection endpoint).

If you're not sure whether your access tokens are in JWT format or are opaque, you can go to OAuth.tools and in the JWT token tab paste your access token. If it's a JWT you will see decoded data on the right hand side. Also, JWTs are long strings which always have three parts separated by dots.

Michal Trojanowski
  • 10,641
  • 2
  • 22
  • 41