ViewSet仅在一项REST操作上使用令牌身份验证(Django Rest)

时间:2018-09-15 22:16:17

标签: django-rest-framework

问题

我正在使用Django Rest Framework。在这种情况下,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)

2 个答案:

答案 0 :(得分:1)

可以为这种方式定义自定义权限类:

class AuthenticatedDelete(BasePermission):
    def has_permission(self, request, view):
        if request.method == 'DELETE':
            if not request.user.is_authenticated():
                return False
        return True

然后将其添加到您的permission_classes

答案 1 :(得分:1)

如下所示覆盖 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