How to get username from Django Rest Framework JWT token

I am using the Django Rest Framework, and I have included a third-party package called the JWT Auth REST framework . It returns a token when you send username / password to a specific route. Then a token is needed to resolve certain routes. However, how to get the username from the token? I went through all the package documentation and went through StackOverflow. This is a JSON Web token, and I assume that there is a method like username = decode_token(token) , but I have not found such a method.

+6
source share
3 answers

You can basically do it

 username = request.user.username 
+4
source

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

I had to do the following to return the user from the 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 middleware that will install the user based on their token.

You can read the walkthrough here: http://blog.sadafnoor.me/blog/a-django-rest-framework-jwt-middleware-to-support-request-user/

+1
source
 from rest_framework_simplejwt.state import token_backend from django.contrib.auth import authenticate, get_user_model payload = token_backend.decode(token, verify=True) user_id = payload.get('user_id') user = User.objects.get(id=user_id) 
0
source

Source: https://habr.com/ru/post/1257625/


All Articles