django - 没有调用 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,结果相同。
解决方案
似乎方法的函数签名authenticate(...)
不正确,应该是
class EmailBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
# do something
推荐阅读
- ruby-on-rails - Rails/PostgreSQL 问题:PG::ConnectionBad:fe_sendauth:未提供密码
- unity3d - 统一的多语言文本框
- azure-devops - 有没有办法在 Azure DevOps 中编写重复性任务的脚本?
- java - 通过将字符串(来自数组)分配为对象的参数之一,将其他参数保留为空,将字符串数组转换为对象列表
- c# - 使用 PredicateBuilder 构建的 IQueryable 中的查询字符串
- python - 在较大的字符串中使用“in”查找字符串
- opengl - 在 glBufferData 之后,非确定性 SSBO 的 GL_BUFFER_DATA_SIZE 太小
- python - 运行其他功能后如何覆盖tkinter中的标签
- php - 动态查询雄辩
- javascript - 识别给定的时间戳