【问题标题】:Custom response for invalid token authentication in Django rest frameworkDjango rest框架中无效令牌认证的自定义响应
【发布时间】:2016-01-17 23:29:17
【问题描述】:

对于下面这段代码,我想返回一个与用户是否通过身份验证相对应的布尔值。

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)

但是,对于无效令牌,控件甚至没有进入 get 方法,因此我无法自定义响应。在这种情况下,我会收到回复:{'detail': 'invalid token'}, 关于如何自定义无效令牌响应的任何想法?

【问题讨论】:

  • 我认为你应该创建一个自定义的 TokenAuthentication 类。

标签: django django-rest-framework django-authentication


【解决方案1】:

这对我有用:

自定义认证类:

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)

查看类:

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)

【讨论】:

  • 如果您有任何允许,那么请求和检查令牌有效性的意义何在
【解决方案2】:

您可以创建一个CustomTokenAuthentication 类并覆盖authenticate_credentials() 方法以在令牌无效的情况下返回自定义响应。

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)

完成此操作后,在您的 DRF 设置中或基于每个视图/视图集定义此自定义令牌身份验证类。

另一个选项是创建一个custom exception handler.,您可以检查引发的异常类型是否为AuthenticationFailed,异常消息是否为'invalid token'。在那里你可以修改异常消息(也可以查看这个官方 DRF example)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-28
    • 2023-03-29
    • 2021-08-03
    • 2016-08-12
    • 2015-08-24
    • 2014-12-24
    • 2021-01-30
    • 1970-01-01
    相关资源
    最近更新 更多