【问题标题】:HTTP 403 in django rest frameworkdjango rest 框架中的 HTTP 403
【发布时间】:2016-02-17 19:45:42
【问题描述】:

所以我有一个基于函数的视图,它与 Django REST 框架一起使用,如下所示:

from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import permission_classes

@api_view(['GET'])
@permission_classes((IsAuthenticated, ))
def example_view(request):
    .....
    <business logic>
    .....

如果权限不足的用户尝试访问绑定到此视图的 URL,这将按预期工作并给出 HTTP 401。但是,由于前端角度的设置方式,我需要显示 HTTP_403(禁止)。我浏览了 DRF 文档,看不到任何可以用作装饰器的已定义权限类。实现此功能的最佳方法是什么?

【问题讨论】:

    标签: python django django-rest-framework decorator


    【解决方案1】:

    所以我找到了解决方案。IsAuthenticated 类对发出 401 和 403 有非常具体的规则,它们如下:

    1. 请求已成功验证,但权限被拒绝。 — 将返回 HTTP 403 Forbidden 响应。
    2. 请求未成功验证,最高优先级验证类不使用 WWW-Authenticate 标头。 — 将返回 HTTP 403 Forbidden 响应。
    3. 请求未成功验证,最高优先级验证类确实使用 WWW-Authenticate 标头。 — 将返回 HTTP 401 Unauthorized 响应,并带有适当的 WWW-Authenticate 标头。

    因此,为了强制 DRF 发出 403,始终只使用不使用 WWW-Authenticate 标头的身份验证类。这就是我最终得到的结果:

    from rest_framework.permissions import IsAuthenticated
    from rest_framework.decorators import permission_classes
    from rest_framework.decorators import authentication_classes
    from rest_framework.authentication import SessionAuthentication, BasicAuthentication
    
    @api_view(['GET'])
    @authentication_classes((SessionAuthentication, BasicAuthentication))
    @permission_classes((IsAuthenticated, ))
    def example_view(request):
        .....
        <business logic>
        .....
    

    【讨论】:

      猜你喜欢
      • 2019-02-22
      • 2022-10-04
      • 1970-01-01
      • 2016-09-23
      • 2018-05-02
      • 2019-06-22
      • 1970-01-01
      • 1970-01-01
      • 2017-11-09
      相关资源
      最近更新 更多