【问题标题】:How to add a django rest framework authentication in Route?如何在 Route 中添加 django rest 框架身份验证?
【发布时间】:2019-10-10 17:11:05
【问题描述】:

如何在Route中添加django rest框架认证?

我正在使用 JWT 对我的应用程序进行身份验证。 一切正常。

我需要知道的是如何基于 REST Framework 和 JWT 对特定路由进行身份验证

例子

from rest_framework.permissions import IsAuthenticated

path(r'modulo/app/aula/<modalidade>', IsAuthenticated  AppAulaAdd.as_view(),     name='app_aula')

from rest_framework.decorators import authentication_classes

path(r'modulo/app/aula/<modalidade>',  authentication_classes(AppAulaAdd.as_view()),     name='app_aula')

两者都不起作用。

【问题讨论】:

  • 你说的 "特定 url" 是什么意思?我不明白
  • 对不起。这将是路线

标签: django django-rest-framework jwt django-rest-framework-jwt


【解决方案1】:

您在问题中混合了概念。权限类根据用户在系统或会话中的状态(即 IsAuthenticated、IsStaff 等)控制对资源的访问,而身份验证类控制对用户进行身份验证的方法,例如 BasicAuthentication 或在您的情况下为 JSONWebTokenAuthentication。此外,您应该直接在视图中添加这两种类型的类,这是更好的做法(来自https://www.django-rest-framework.org/api-guide/authentication/)

class ExampleView(APIView):
    authentication_classes = (SessionAuthentication, BasicAuthentication)
    permission_classes = (IsAuthenticated,)

但如果出于某种原因,100% 需要在您的 urls 文件(路由)中添加权限,您可以执行以下操作:

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

path(r'modulo/app/aula/<modalidade>', (permission_classes([IsAuthenticated])(AppAulaAdd)).as_view(), name='app_aula')

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2013-06-29
    • 2017-09-26
    • 2017-11-02
    • 2019-03-01
    • 2021-12-21
    • 1970-01-01
    • 2015-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多