针对通用API视图的特定方法进行身份验证

时间:2018-06-28 05:06:59

标签: django authentication django-rest-framework

我已将ListCreateAPIViewRetrieveUpdateDestroyAPIView用于模型。现在,我想将 JWT 身份验证仅添加到RetrieveUpdateDestroyAPIView中的更新并销毁部分。我该怎么办?


让我让我的问题更加清楚。我有一个名为Post的模型。现在,所有用户都可以查看该帖子,但更新,删除仅对创建该帖子的用户可用。而且我想使用 JWT身份验证

2 个答案:

答案 0 :(得分:0)

您可以为此编写custom permission类:

from rest_framework import permissions

class CustomPermission(permissions.BasePermission):
    def has_permission(self, request, view):
        if view.action in ('update', 'destroy'):
            return request.user.is_authenticated
        return True

并在您的视图中使用:

class ExampleView(RetrieveUpdateDestroyAPIView):
    permission_classes = (CustomPermission,)

答案 1 :(得分:0)

我们可以覆盖方法get_authenticators,并且不要忘记将authentication_classes添加到a​​pi视图。

def get_authenticators(self):
    if self.request.method in ['PUT', 'DELETE']:
        return [auth() for auth in self.authentication_classes]
    else:
        return [] 

对于您的问题更新,我们需要添加如下所示的对象级别权限

class OwnerRequiredPermission(object):

     def has_object_permission(self, request, obj):
          return obj.created_by == request.user

将上述权限类别添加到permission_classes

相关问题