Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

how to load user from jwt token request django

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
Comment

get jwt user in django

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)
Comment

PREVIOUS NEXT
Code Example
Python :: skimage local threshold 
Python :: python change audio output device 
Python :: Use CSS in PHP Echo with Style Attribute 
Python :: remove element from list by index 
Python :: convert .py to exe 
Python :: random chars generator python 
Python :: pandas create sample dataframe 
Python :: DJANGO rest framework GET POST 
Python :: python convert string to list 
Python :: install pocketsphinx error 
Python :: creating django app 
Python :: python make 1d array from n-d array 
Python :: python multiply 2 variables 
Python :: console-based animation-simple 
Python :: jupyter today date 
Python :: python discord bot 
Python :: python check if number in string 
Python :: merge two netcdf files using xarray 
Python :: check runtime python 
Python :: Python List count() example 
Python :: while input is not empty python 
Python :: TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use .set() instead 
Python :: abstract class python 
Python :: how to append to a dictionary in python 
Python :: models in django 
Python :: python how to print something at a specific place 
Python :: how to remove an element from dictionary using his value python 
Python :: python region 
Python :: freecodecamp python 
Python :: save imag epillow 
ADD CONTENT
Topic
Content
Source link
Name
4+2 =