django - 如何在 Route 中添加 django rest 框架身份验证?
问题描述
如何在 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')
两者都不起作用。
解决方案
您在问题中混合了概念。权限类根据用户在系统或会话中的状态(即 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')
希望能帮助到你。
推荐阅读
- apache-spark - Spark 2.X:使用 Spark SQL 查询 Hive 表时由 Spark 作业设置的任务数
- java - Java 应用程序与 node.js 服务器通信的最佳反应方式
- javascript - 从 @types 类型修改 TypeScript 类型别名
- dart - 在图标点击上渲染屏幕
- node.js - 从 nodejs 向第三方 API 请求的性能瓶颈
- python - 线程类不会启动或初始化
- java - Java 不能从原始泛型类型列表转换为通配符泛型类型列表
- azure - Azure Functions VS 部署环境变量
- sql - 我有一个关系型和星型模式数据模型,我想查询以下结果
- xcode - 为什么我需要 Xcode 来安装一些软件包