I cannot authenticate user with the jwt token in my django project

68 Views Asked by At

I'm trying to authenticate a user with jwt token generated in the login view, while copying the jwt token and adding it into the headers for authorization it shows an error and doesn't get authorized:

{
    "detail": "Given token not valid for any token type",
    "code": "token_not_valid",
    "messages": [
        {
            "token_class": "AccessToken",
            "token_type": "access",
            "message": "Token is invalid or expired"
        }
    ]
}

This is my custom user model

class CUser(AbstractBaseUser):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255)
    email = models.EmailField(unique=True)
    password = models.CharField(max_length=255)
    dob = models.DateField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now=True)
    
    #username = None
    
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []
# models.py
class loginapi(APIView):

    def post(self, request):
        try:
            data = request.data
            serializer = LoginSerializer(data=data)
            if serializer.is_valid():
                email = request.data['email']
                password = request.data['password']
    
                user = CUser.objects.filter(email=email).first() #check for user.
    
                if user is None:
                    return Response({
                        'status':400,
                        'message':'User not found',
                        'data': {}
                    })
                
                if not user.check_password(password):
                    return Response({
                        'status':400,
                        'message':'Wrong password',
                        'date': {}
                    })
                
    
                payload = {
                    'id': user.id,
                    'exp': timezone.now() + datetime.timedelta(minutes=60),
                    'iat': timezone.now()
                }
    
                token = jwt.encode(payload, 'secret', algorithm='HS256')
                #token_string = token.decode('utf-8')
                response = Response()
                response.set_cookie(key='jwt', value=token, httponly=True)      
                response.data = {
                    'jwt':token
                }
                return response
            return Response({
                        'status':400,
                        'message':'Something went wrong',
                        'date': serializer.errors
            })
        except Exception as e:
            return Response({'message': str(e)}, status=400)
```output(print(payload)): eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTEsImV4cCI6MTcxMTM0ODI0NSwiaWF0IjoxNzExMzQ0NjQ1fQ.iRoq_kPox_N_tPXjFUlhaycPMPpR6kA5QCtC-bNIAy4
```
class userapi(APIView):
   def get(self, request):
   token = request.COOKIES.get('jwt')
   if not token:
      raise AuthenticationFailed('Unauthenticated')
   try:
      payload = jwt.decode(token, 'secret', algorithms=\['HS256'\])
      print(payload) 
      except jwt.ExpiredSignatureError:
          raise AuthenticationFailed('Unauthenticated')
      user = CUser.objects.filter(id=payload\['id'\]).first()
      serializer = UserSerializer(user)
   return Response(serializer.data)

these are my login and user views this is the jwt token that's getting generated

{
"jwt":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTEsImV4cCI6MTcxMDk5OTAwNCwiaWF0IjoxNzEwOTk1NDA0fQ.DEY0obelNmMfCsDy1Pv_1w7SAiCwEnmGDKbC6Zz9oxs"
}

hope you can help me out now.

0

There are 0 best solutions below