首页 > 解决方案 > ViewSet 仅在一个 REST 操作(Django Rest)中使用令牌身份验证

问题描述

问题

我正在使用 Django 休息框架。在那种情况下,一个ViewSet. 仅在我想使用的一项 REST 操作上Token Authentication。DRF是否提供甚至提供类似的东西?

感谢您的帮助。

 class UserProfileViewSet(viewsets.ModelViewSet):
      queryset = UserProfile.objects.all()
      serializer_class = UserProfileSerializer

      #Here the Token Authentication should be
      def destroy(self, request, pk=None, **kwargs):
          try:
              user = User.objects.get(pk=pk)
              user.delete()
          except User.DoesNotExist:
              return Response(status=status.HTTP_400_BAD_REQUEST)
          return Response(status=status.HTTP_204_NO_CONTENT)

标签: django-rest-framework

解决方案


覆盖该get_authenticators()方法如下。该get_authenticators()方法实例化并返回此视图可以使用的身份验证器列表。在您的情况下,该方法将返回/验证TokenAuthentication如果操作是破坏,(HTTP DELETE

from rest_framework.authentication import TokenAuthentication


class UserProfileViewSet(viewsets.ModelViewSet):
    # your code
    authentication_classes = (TokenAuthentication,)

    def get_authenticators(self):
        if self.action == 'destroy':
            return super().get_authenticators()
        return []

    def destroy(self, request, pk=None, **kwargs):
        # your code

推荐阅读