authenticate() 不是 运行 自定义身份验证后端

authenticate() is not running with custom authentication backend

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

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

settings.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,但是 AUTH 或 [=32] 的 none =]GETUSER 个字符串。

可能是什么原因?

主要 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'),

...

我错过了什么?我在 Internet 上阅读了很多关于它的问题和帖子,但我不明白为什么根本没有调用 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