12👍
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)
- [Django]-Django related_name for field clashes
- [Django]-How to add new languages into Django? My language "Uyghur" or "Uighur" is not supported in Django
- [Django]-How to make an auto-filled and auto-incrementing field in django admin
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.
- [Django]-Do we need to upload virtual env on github too?
- [Django]-How do I run tests against a Django data migration?
- [Django]-Switching to PostgreSQL fails loading datadump
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 !!
- [Django]-Python 3 list(dictionary.keys()) raises error. What am I doing wrong?
- [Django]-Django apps aren't loaded yet when using asgi
- [Django]-Sending HTML email in django
Source:stackexchange.com