首页 > 解决方案 > 没有调用 django 自定义身份验证后端

问题描述

我正在使用 Django 3.1,并试图弄清楚为什么我的自定义身份验证后端没有被调用。

在我的 settings.py 文件中,我有:

AUTHENTICATION_BACKENDS = (
    'sizzy.backends.EmailBackend',
)

在我的 sizzy.backends.py 文件中,我有:

from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.backends import ModelBackend
from .models import User

class EmailBackend(ModelBackend):
    def authenticate(self, username=None, password=None):
        try:
            print("Trying the email backend!")
            user = User.objects.get(email=username)
            print("Got the user")
            if user.check_password(password): # check valid password
                return user
            print("password didn't work")
        except ObjectDoesNotExist:
            return None

    def get_user(self, user_id):
        try:
            print("Getting the user of the Email Bkacned")
            return User.objects.get(pk=user_id)
        except ObjectDoesNotExist:
            return None

然后我打开manage.py shell并输入:

from django.contrib.auth import authenticate
email = "billypop@a.pop"
password = "password"
user = authenticate(username=email, password=password)

它输出:

Login failed. Credentials:
{'username': 'billypop@a.pop', 'password': '********************'}

而且我没有看到任何打印语句。“尝试获取电子邮件后端!” 从不打印。我错过了什么吗?我尝试更改我的设置文件以指向sizzy.backends.EmailBackendqwertyui只是作为健全性检查,这引发了错误而不是登录失败。所以我认为后端正在以某种方式加载,但从未调用过。

我还尝试将 ModelBackend 更改为 BaseBackend,结果相同。

标签: djangodjango-authentication

解决方案


似乎方法的函数签名authenticate(...)不正确,应该是

class EmailBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        # do something

推荐阅读