[Django]-Custom response for invalid token authentication in Django rest framework

3πŸ‘

βœ…

This worked for me:

Custom Authentication class:

class MyAuthentication(authentication.TokenAuthentication):
    def authenticate_credentials(self, key):
        try:
            token = self.model.objects.select_related('user').get(key=key)
        except self.model.DoesNotExist:
            return (None, '')

        if not token.user.is_active:
            raise exceptions.AuthenticationFailed(_('User inactive or deleted.'))

        return (token.user, token)

view class:

class UserAuthenticatedView(APIView):
    authentication_classes = (MyAuthentication,)
    permission_classes = (AllowAny,)

    def get(self, request, format=None):
        is_authenticated = False
        if request.user and request.user.is_authenticated():
            is_authenticated = True
        resp = {'is_authenticated': is_authenticated}
        return Response(resp, content_type="application/json", status=status.HTTP_200_OK)
πŸ‘€Saurabh Verma

4πŸ‘

You can create a CustomTokenAuthentication class and override the authenticate_credentials() method to return the custom response in case of invalid token.

class CustomTokenAuthentication(TokenAuthentication):

    def authenticate_credentials(self, key):
        try:
            token = self.model.objects.select_related('user').get(key=key)
        except self.model.DoesNotExist:
            # modify the original exception response
            raise exceptions.AuthenticationFailed('Custom error message') 

        if not token.user.is_active:
            # can also modify this exception message
            raise exceptions.AuthenticationFailed('User inactive or deleted')

        return (token.user, token)

After doing this, define this custom token authentication class in your DRF settings or on a per-view/viewset basis.

Another option is to create a custom exception handler. In that, you can check if the exception raised was of type AuthenticationFailed and the exception message is 'invalid token'. There you can modify the exception message (also check this official DRF example).

πŸ‘€Rahul Gupta

Leave a comment