Search code examples
djangodjango-rest-frameworkdjango-rest-framework-simplejwt

Customized Django SimpleJWT Views


I am using a django-simplejwt and I have a custom token view for obtaining token. My problem is, how can i override the 401 Unauthorized response from the view?

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

from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView

class ObtainTokenSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)


        # Add custom claims
        token['name'] = user.first_name
        # ...

        return token

class ObtainToken(TokenObtainPairView):
    serializer_class = ObtainTokenSerializer

enter image description here


Solution

  • The answer might resides in the Exception raised.

    As you dive in the simplejwt package you'd see something as following :

    class InvalidToken(AuthenticationFailed):
        status_code = status.HTTP_401_UNAUTHORIZED
        default_detail = _('Token is invalid or expired')
        default_code = 'token_not_valid'
    

    This is where comes from the 401 you see.

    Therefore your class ObtainToken should override the post method from the mother class TokenViewBase with you specific Exception or Response.

    For example :

    from rest_framework import status
    ...
    
    class ObtainToken(TokenObtainPairView):
        serializer_class = ObtainTokenSerializer
        ...
        def post(self, request):
            serializer = self.serializer_class(
                data=request.data, 
                context={'request': request}
            )
    
            try:
                serializer.is_valid()
    
                return Response(
                    serializer.validated_data,
                    status=status.HTTP_200_OK
                )
            except Exception:
                return Response(status=status.HTTP_404)
    

    Although above is just an example, you should implement something similar as the post method from TokenViewBase but with your customized status and data.