我正在尝试使用以下版本和代码片段向我的项目添加新的身份验证后端:
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,但没有取回 AUTH 或 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'),
...
我错过了什么?我在互联网上阅读了很多有关它的问题和帖子,但我不明白为什么根本不调用 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/