How To Load User From Jwt Token Request Django

[Solved] How To Load User From Jwt Token Request Django | Basic - Code Explorer | yomemimo.com
Question : how to load user from jwt token request django

Answered by : mohaimanul-islam

from django.conf import settings
from rest_framework import authentication
from rest_framework import exceptions
from rest_framework.authentication import get_authorization_header
import CustomUser # just import your model here
import jwt
class JWTAuthentication(authentication.BaseAuthentication): def authenticate(self, request): # it will return user object try: token = get_authorization_header(request).decode('utf-8') if token is None or token == "null" or token.strip() == "": raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers') print(token) decoded = jwt.decode(token, settings.SECRET_KEY) username = decoded['username'] user_obj = CustomUser.objects.get(username=username) except jwt.ExpiredSignature : raise exceptions.AuthenticationFailed('Token Expired, Please Login') except jwt.DecodeError : raise exceptions.AuthenticationFailed('Token Modified by thirdparty') except jwt.InvalidTokenError: raise exceptions.AuthenticationFailed('Invalid Token') except Exception as e: raise exceptions.AuthenticationFailed(e) return (user_obj, None) def get_user(self, userid): try: return CustomUser.objects.get(pk=userid) except Exception as e: return None

Source : https://stackoverflow.com/questions/50405425/django-jwt-get-user-info | Last Update : Wed, 26 Jan 22

Question : get jwt user in django

Answered by : mohaimanul-islam

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=False) user = valid_data['user'] request.user = user except ValidationError as v: print("validation error", v)

Source : https://stackoverflow.com/questions/39823363/how-to-get-username-from-django-rest-framework-jwt-token | Last Update : Wed, 26 Jan 22

Answers related to how to load user from jwt token request django

Code Explorer Popular Question For Basic