Gary Holiday
Gary Holiday

Reputation: 3582

How to get username from Django Rest Framework JWT token

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.

Upvotes: 21

Views: 34968

Answers (4)

Bhavik Agarwal
Bhavik Agarwal

Reputation: 31

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 !!

Upvotes: 3

Arpan Kushwaha
Arpan Kushwaha

Reputation: 331

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)

Upvotes: 13

sadaf2605
sadaf2605

Reputation: 7550

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.

Upvotes: 11

Sardorbek Imomaliev
Sardorbek Imomaliev

Reputation: 15400

Basically you could do this

username = request.user.username

Upvotes: 15

Related Questions