How to get username from Django Rest Framework JWT token
Asked Answered
G

4

21

I am using Django Rest Framework and i've included a 3rd party package called REST framework JWT Auth. It returns a token when you send a username/password to a certain route. Then the token is needed for permission to certain routes. However, how do I get the username from the token? I've looked all through the package documentation and went through StackOverflow. It is a JSON Web Token and I am assuming there is a method like username = decode_token(token) but I haven't found such a method.

Gracious answered 3/10, 2016 at 1:18 Comment(3)
You have user object in request. Or you are not doing this in view?Jigging
I am doing this in view but I am new to Django so I don't fully understand how it works. Can you elaborate?Gracious
Add your view codeJigging
J
15

Basically you could do this

username = request.user.username
Jigging answered 3/10, 2016 at 5:53 Comment(9)
Seriously ? @sardorbek Why did you edit my code. I am using Camel Case type of coding. Is it really necessary to code with _ ?. There was no need.Arman
@PrakharTrivedi read pep8 guidlines python.org/dev/peps/pep-0008. It is convention for python communityJigging
Yeah,I agree with that. But was is really necessary ? There are much better things to do than this.Arman
@PrakharTrivedi You are answering question of beginner python developer. It is necessary to write answer which complies with python guidlines, because he will copy and paste your code and he will think that this kind of coding style is ok, which is not for our community.Jigging
Okay Sardorbek. Duly noted (no pun intended). Will keep this in mind from next time.Arman
@PrakharTrivedi thank you) I just want StackOverflow to be as good as possible.Jigging
Hello Sardorbek. Can you tell where to use this in your DRF Code ? In View? Serializers ? Thanks.Melinamelinda
@Addict this can be used everywhere, where request object is passed, but usually this is done in a viewJigging
It will not work in JWT.Pe
A
13

For me, this worked as RestFrameworkJWT is no longer maintained. So I used the rest_framework_simplejwt package.

from rest_framework_simplejwt.backends import TokenBackend
token = request.META.get('HTTP_AUTHORIZATION', " ").split(' ')[1]
data = {'token': token}
   try:
      valid_data = TokenBackend(algorithm='HS256').decode(token,verify=True)
      user = valid_data['user']
      request.user = user
   except ValidationError as v:
      print("validation error", v)
Acquiesce answered 26/10, 2020 at 10:22 Comment(3)
verifty=False - Disabling token verification is insecure, don't do this.Landgraviate
Editing the ans as suggested. @LandgraviateAcquiesce
"Disabling token verification is insecure, don't do this" -> except if you just need to decode a JWT. In my case the authentication is done at another level and my backend does not have the jwt secret key. This answer is very useful.Jaysonjaywalk
S
11

For me with Django (2.0.1), djangorestframework (3.7.7), djangorestframework-jwt (1.11.0).

I had to do following to get my use back user from token:

        token = request.META.get('HTTP_AUTHORIZATION', " ").split(' ')[1]
        print(token)
        data = {'token': token}
        try:
            valid_data = VerifyJSONWebTokenSerializer().validate(data)
            user = valid_data['user']
            request.user = user
        except ValidationError as v:
            print("validation error", v)

Or you can write a middleware that would set user based on their token.

Schnitzler answered 2/4, 2018 at 7:39 Comment(2)
I'm getting errors can you please share ur entire middleware fileHarryharsh
Sorry, this is not what the user has asked for. But you can visit the link, it has entire middleware.Schnitzler
K
3

If you are using djangorestframework_simplejwt, to get user object from JWT Token you need to do the following :

token = AccessToken(access_token)
user_id = token.payload['user_id']
user = User.objects.get(id=user_id)

This works well !!

Kook answered 28/6, 2023 at 7:7 Comment(1)
you didn't include your imports, you didnt include the access_token declaration. this response can be imporved more and better to guidd people in the future once they come accross this answer.Tolland

© 2022 - 2024 — McMap. All rights reserved.