未调用 Django 自定义身份验证后端
django custom authentication backend is not being called
我正在使用 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(<b>self, request, username=None, password=None, **kwargs</b>):
# do something
我正在使用 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(<b>self, request, username=None, password=None, **kwargs</b>):
# do something