Skip to main content
 首页 » 编程设计

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

2025年05月04日27jpfss

我们使用 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]:可以通过 SessionAuthentication 和其他类似的 DRF 后端使用 Django 身份验证后端。