Djangorestframework-simplejwt: How to get user object via access_token?

Created on 22 Jul 2019  路  4Comments  路  Source: jazzband/djangorestframework-simplejwt

Can I get the user object via access token?

Most helpful comment

It depends on what you have access to in the current scope. If you're in the code of an authenticated view, your user has already been determined by django and the jwt plugin. You'd do something like this:

def my_view(request):
    request.user

If all you have is the base64 encoded access token string, you can decode it using the AccessToken class:

from restframework_simplejwt.tokens import AccessToken

token_str = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiY29sZF9zdHVmZiI6IuKYgyIsImV4cCI6MTIzNDU2LCJqdGkiOiJmZDJmOWQ1ZTFhN2M0MmU4OTQ5MzVlMzYyYmNhOGJjYSJ9.NHlztMGER7UADHZJlxNG0WSi22a2KaYSfd1S-AuT7lU'
access_token = AccessToken(token_str)
user = User.objects.get(access_token['user_id'])

All 4 comments

I have the same question.

It depends on what you have access to in the current scope. If you're in the code of an authenticated view, your user has already been determined by django and the jwt plugin. You'd do something like this:

def my_view(request):
    request.user

If all you have is the base64 encoded access token string, you can decode it using the AccessToken class:

from restframework_simplejwt.tokens import AccessToken

token_str = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiY29sZF9zdHVmZiI6IuKYgyIsImV4cCI6MTIzNDU2LCJqdGkiOiJmZDJmOWQ1ZTFhN2M0MmU4OTQ5MzVlMzYyYmNhOGJjYSJ9.NHlztMGER7UADHZJlxNG0WSi22a2KaYSfd1S-AuT7lU'
access_token = AccessToken(token_str)
user = User.objects.get(access_token['user_id'])

user = User.objects.get(id=access_token['user_id']) , works fine.
@davesque Thank you.

@xianfuxing How come the authentication framework isn't giving you a user object on the request?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

selmanceker picture selmanceker  路  3Comments

ethanjahn picture ethanjahn  路  7Comments

mosi-kha picture mosi-kha  路  6Comments

robd003 picture robd003  路  6Comments

mjackstone6 picture mjackstone6  路  4Comments