python - Django REST Framework TokenAuthentication 通常在 Django 中进行身份验证

标签 python django django-rest-framework

我们使用 rest_framework.authentication.TokenAuthentication 通过访问 token 对 Django REST Framework 中的 API 用户进行身份验证。

有没有办法使用同一个类来验证 Django 用户的身份?

我尝试将其直接添加到 AUTHENTICATION_BACKENDS 中,但不起作用:

AUTHENTICATION_BACKENDS = (
    # Needed to login by username in Django admin, regardless of `allauth`
    "django.contrib.auth.backends.ModelBackend",

    # `allauth` specific authentication methods, such as login by e-mail
    "allauth.account.auth_backends.AuthenticationBackend",

    'rest_framework.authentication.TokenAuthentication',
)

有没有快速的方法来做到这一点,或者我需要编写自定义身份验证后端吗?

最佳答案

Django REST 框架身份验证和权限类需要使用 Django REST 框架 View ,因为身份验证是在 View 级别 [1] 上完成的。这与 Django 身份验证后端不同,后者的身份验证是通过中间件完成的。

Is there a way to use this same class to authenticate users for Django generally?

不,Django REST 框架身份验证后端与 Django 身份验证后端明显分开,技术上相反[2]

[1]:已经讨论过将其移至中间件级别,但目前尚未计划。
[2]:Django 身份验证后端可以通过 SessionAuthentication 和其他类似的 DRF 后端使用。

关于python - Django REST Framework TokenAuthentication 通常在 Django 中进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30125536/

相关文章:

python - 删除 django 模板中的 [u'']

django - 从结果中排除整个QuerySet

django-rest-framework 身份验证 : require key parameter in URL?

Django REST Framework 请求中的 bool 值/无值设置为 False

Django Rest 框架错误 : {"user": ["This field is required."]

python - Django 创建自定义用户模型

python - 创建一个新的终端/shell 窗口以简单地显示文本

python - 将列表中的每个项目加倍

python - AWS Elastic Beanstalk 上的 Django - 没有名为 MySQLdb 的模块错误

python - Django 从objects.all() 生成无用的JSON 对象