django - Django Rest 框架中无效 token 身份验证的自定义响应

标签 django django-rest-framework django-authentication

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

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)

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

最佳答案

您可以创建一个 CustomTokenAuthentication 类并重写 authenticate_credentials() 方法,以便在 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)

完成此操作后,在 DRF 设置中或基于每个 View / View 集定义此自定义 token 身份验证类。

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

关于django - Django Rest 框架中无效 token 身份验证的自定义响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33217441/

相关文章:

django - 如何为已获取的列表预获取相关对象?

python - Django/Python 应用程序和开发环境的先决条件

python - Django 单元测试;使用 python-social-auth 登录

python - 覆盖身份验证方法 - Django admin

python - 无法在 CPanel 上上传媒体文件(使用 django)

django - 从动态 ModelForm 中删除字段

django - 在 django-rest 框架中使用原始 SQL?

通过API上传Django文件

python - Django休息框架: Validate a related field with a list of IDs

python - 使用 django-allauth 扩展 Django 用户模型