Getting user details from access token in Django rest framework -simple JWT

Viewed 5683

I am using React and Django rest framework for a project. I use Django rest framework simple JWT for authentication. Now, I want to display the username in the navbar after the user logs in. So, is there a way in simple JWT for returning user details from the access token generated after authentication, just like Djoser returns user credentials when supplied the access token?

Sorry if this question is silly but I was not able to find a solution to this anywhere.

2 Answers

if you want to obtain the information of the owner of the token you can consult it in REQUEST.

class ViewProtect(APIView):
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]

    def post(self, request, format=None):
        token_user_email = request.user.email
        token_user_username = request.user.username
        pass

About the backend, basically I use this library

from restframework_simplejwt.tokens import AccessToken

The function AccessToken() take as input the string access_token_str and return the object access_token_obj.

To get the user_id, you can use the instruction

user_id=access_token_obj['user_id'].

In the following example I have created the function

get_user_from_access_token_in_django_rest_framework_simplejwt().

This function is just a wrapper around AccessToken()

Full code:

#Path current file
#/blabla/django/project004/core/view.py


from restframework_simplejwt.tokens import AccessToken
from django.contrib.auth.models import User

#Example data.
#access_token_str = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiY29sZF9zdHVmZiI6IuKYgyIsImV4cCI6MTIzNDU2LCJqdGkiOiJmZDJmOWQ1ZTFhN2M0MmU4OTQ5MzVlMzYyYmNhOGJjYSJ9.NHlztMGER7UADHZJlxNG0WSi22a2KaYSfd1S-AuT7lU'
def get_user_from_access_token_in_django_rest_framework_simplejwt(access_token_str):
    access_token_obj = AccessToken(access_token_str)
    user_id=access_token_obj['user_id']
    user=User.objects.get(id=user_id)
    print('user_id: ', user_id )
    print('user: ', user)
    print('user.id: ', user.id )
    content =  {'user_id': user_id, 'user':user, 'user.id':user.id}
    return Response(content)

Credits:

@davesque;
https://github.com/jazzband/djangorestframework-simplejwt/issues/140

Update. The string access_token_str I write in the file is just an example. You should pass it as argument.

Related