python - authenticate() 未与自定义身份验证后端一起运行

标签 python django authentication django-authentication

我正在尝试使用以下版本和代码片段向我的项目添加新的身份验证后端:

Django:2.2.1 python :3.5.2 mysql-服务器:5.7

设置.py

...
AUTHENTICATION_BACKENDS = ['common.backends.MyOwnAuthenticationBackend']

common/backends.py

from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User


class MyOwnAuthenticationBackend(ModelBackend):
    print('MOAB')
    def authenticate(self, username=None, password=None):
        print('AUTH')
        ...

    def get_user(self, username):
        print('GETUSER')
        try:
            return User.objects.get(pk=username)
        except User.DoesNotExist:
            return None

尝试登录时,我取回了 MOAB,但没有取回 AUTHGETUSER 字符串。

这可能是什么原因?

主 urls.py 包含以下用于身份验证的内容:

urls.py

from common import views as common_views
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views
from django.urls import path

...

url(r'^accounts/login/$', views.LoginView, name='auth_login'),

...

我错过了什么?我在互联网上阅读了很多有关它的问题和帖子,但我不明白为什么根本不调用 authenticate() 方法。

最佳答案

该方法应如下所示:

def authenticate(self, request, username=None, password=None):

您可以通过查看source of authentication system来检查方法authenticate签名所需的参数。 。第一个定位参数是 request,然后凭据将被解包为命名参数:

def authenticate(request=None, **credentials):
    """
    If the given credentials are valid, return a User object.
    """
    for backend, backend_path in _get_backends(return_tuples=True):
        try:
            inspect.getcallargs(backend.authenticate, request, **credentials)
        except TypeError:
            # This backend doesn't accept these credentials as arguments. Try the next one.
            continue
        try:
            user = backend.authenticate(request, **credentials)
     [...]

(_get_backends表示settings.AUTHENTICATION_BACKENDS中所有后端的列表)

有关自定义身份验证的文档:
https://docs.djangoproject.com/en/dev/topics/auth/customizing/#writing-an-authentication-backend

关于python - authenticate() 未与自定义身份验证后端一起运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57169222/

相关文章:

javascript - AJAX django 获取请求

c# - ADFS 主动身份验证 .NET 4.5(后 WIF)

reactjs - 在 react SPA 中自动登录的 localStorage 中 JWT 的替代方案?

django - 为什么docker容器中的Django不起作用?

php - Laravel API 身份验证(护照)隐式授予 token - 401 错误

python - 如何居中Python打印

python - 如何在 numpy 中创建递增的多维数组

python - UUIDField 的 Django 1.10 全文搜索返回 DataError

python - 在 Python 中从字符串中提取多个数字

python - django 是否已经附带了 wsgi 应用程序文件,还是我需要创建一个?如何使用 django 设置 apache 和 mod_wsgi?