【问题标题】:Django rest framework global permission not working with custom permission at ViewsetDjango 休息框架全局权限不适用于 Viewset 的自定义权限
【发布时间】:2021-05-23 01:51:52
【问题描述】:

这是我的默认权限类的全局配置,已配置为使用 IsAuthenticated 权限。

    REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': ['rest_framework.authentication.SessionAuthentication',
                                       'rest_framework.authentication.TokenAuthentication', ],

    'DEFAULT_PERMISSION_CLASSES': ['rest_framework.permissions.IsAuthenticated', ],
    }

我希望经过身份验证的用户能够访问我的 API,因此,我在设置中全局配置了 IsAuthenticated 权限。我创建了另一个 IsAuthorOrReadOnly 自定义权限,它只允许 Post 的作者更新、删除,否则只能读取。这是我的视图集。

class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer
    permission_classes = [IsAuthorOrReadOnly]

然而,匿名/每个用户都可以访问 PostViewSet API。全局 Isauthenticated 权限不起作用。当我在 PostViewSet 的 permission_classes 上添加 IsAuthenticated 时,它可以工作。

不应该不管实现的自定义权限,全局配置的权限在项目中是否生效? 为什么全局配置的权限不能和 ViewSets 中的自定义权限一起使用?

【问题讨论】:

    标签: django-rest-framework permissions django-rest-auth django-rest-viewsets


    【解决方案1】:

    DRF 文档说:

    注意:当您通过类属性或设置新的权限类时 您告诉视图忽略默认列表设置的装饰器 settings.py 文件。

    因此,在您的情况下,IsAuthorOrReadOnly 会覆盖设置中定义的那个。

    链接: https://www.django-rest-framework.org/api-guide/permissions/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-22
      • 1970-01-01
      • 2023-03-18
      • 2016-01-10
      • 1970-01-01
      • 2013-09-28
      相关资源
      最近更新 更多