Ami*_*tad 4 python django decorator django-rest-framework
所以我有一个基于函数的视图,我与 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>
.....
Run Code Online (Sandbox Code Playgroud)
这按预期工作,如果权限不足的用户尝试访问绑定到此视图的 URL,则会提供 HTTP 401。但是,由于前端角度的设置方式,我需要的是显示 HTTP_403(禁止)。我浏览了 DRF 文档,但看不到任何可以用作装饰器的已定义权限类..实现这一点的最佳方法是什么?
所以我找到了一个解决方案。IsAuthenticated类有关于发出 401 和 403 的非常具体的规则,它们如下:
- 请求已成功通过身份验证,但权限被拒绝。— 将返回 HTTP 403 Forbidden 响应。
- 请求未成功通过身份验证,并且最高优先级的身份验证类不使用 WWW-Authenticate 标头。— 将返回 HTTP 403 Forbidden 响应。
- 请求未成功通过身份验证,并且最高优先级的身份验证类确实使用 WWW-Authenticate 标头。— 将返回带有适当 WWW-Authenticate 标头的 HTTP 401 Unauthorized 响应。
因此,为了强制 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>
.....
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5661 次 |
| 最近记录: |