Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error decoding signature in Django Rest Framework

I use JWT in my API. But I can't authenticate with JWT. What is the problem I couldn't find. Thanks for your helps.

@api_view(['POST'])
@permission_classes((AllowAny,))
def UserLogin(request):
    try:
        username = request.POST.get('username', None)
        password = request.POST.get('password', None)
        account = authenticate(username=username, password=password)

    except (User.DoesNotExist, User.PasswordDoesNotMatch):
            return Response({'message': 'Wrong credentials'}, status=400)
    if account is not None:
        if account.is_active:
            login(request, account)
            if request.user.is_superuser:
                    user_type = '0'
            elif request.user.is_instructor():
                    user_type = '1'
            elif request.user.is_student():
                    user_type = '2'
            else:
                    user_type = '3'

            payload = {
                    'user_type': user_type,
                    'username': username,
                    'exp': datetime.utcnow() + timedelta(seconds=JWT_EXP_DELTA_SECONDS)
                }
            jwt_token = jwt.encode(payload, JWT_SECRET, JWT_ALGORITHM)
            return Response({'token': jwt_token.decode('utf-8')})

Payload data returns

{
  "user_type": "0",
  "username": "bus",
  "exp": 1475480008
}

It is enough for me. But when I request Other API url, It returns

{
  "detail": "Error decoding signature."
}
like image 223
bysucpmeti Avatar asked Mar 18 '26 23:03

bysucpmeti


1 Answers

The best thing I can suggest to you is not to implement the JWT logic by yourself. Please use the package dj_rest_auth or if you only need the JWT logic, use SimpleJWT. The dj_rest_auth package provides you with full-featured functionalities for authentication and authorization. It also uses SimpleJWT by default as its backend for JWT implementation and functionalities.

Links:

https://dj-rest-auth.readthedocs.io/en/latest/

https://django-rest-framework-simplejwt.readthedocs.io/en/latest/

like image 124
Mohammad Mahdi Mohajer Avatar answered Mar 20 '26 13:03

Mohammad Mahdi Mohajer