Custom response for invalid token authentication in Django rest framework

不羁岁月 提交于 2019-12-24 00:23:56

问题


For the following piece of code, I would like to return a boolean corresponding to whether the user was authenticated or not.

class UserAuthenticatedView(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = (AllowAny,)
    def get(self, request, format=None):
        is_authenticated = request.user.is_authenticated()
        resp = {'is_authenticated': is_authenticated}
        return Response(resp, content_type="application/json", status=status.HTTP_200_OK)

However, for invalid token, the control is not not even going inside get method due to which I'm not able to customize the response. In such a case I'm getting the response: {'detail': 'invalid token'}, Any idea on how to customize the response for invalid token ?


回答1:


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




回答2:


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)


来源:https://stackoverflow.com/questions/33217441/custom-response-for-invalid-token-authentication-in-django-rest-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!