正如标题所述,我正在尝试在没有密码的情况下对用户进行身份验证。我已经使用了这个:没有密码的django身份验证来解决我的一些应用程序(在django 2.0上(的问题,但我想在另一个应用程序中做同样的事情,但它在Djano 2.1上。当我执行相同的实现时,我的自定义身份验证函数永远不会被调用。因此,它不起作用。
auth_backend.py中的当前设置:
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
class PasswordlessAuthBackend(ModelBackend):
"""Log in to Django without providing a password.
"""
def authenticate(self, username=None):
try:
return User.objects.get(username=username)
except User.DoesNotExist:
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
设置.py:
AUTHENTICATION_BACKENDS = [
# auth_backend.py implementing Class PasswordlessAuthBackend inside yourapp folder
'yourapp.auth_backend.PasswordlessAuthBackend',
# Default authentication of Django
'django.contrib.auth.backends.ModelBackend',
]
但当我尝试在我的观点
user = authenticate(username=user.username)
它从未命中我的自定义身份验证方法。感谢您的帮助!
您在settings.py 中的Auth后端路径无效
yourapp.auth_backend.YourAuth
应该是
yourapp.auth_backend.PasswordlessAuthBackend
您可以尝试避开默认的后端吗。
更改
AUTHENTICATION_BACKENDS = [
# auth_backend.py implementing Class PasswordlessAuthBackend inside yourapp folder
'yourapp.auth_backend.PasswordlessAuthBackend',
# Default authentication of Django
'django.contrib.auth.backends.ModelBackend',
]
至
AUTHENTICATION_BACKENDS = [
# auth_backend.py implementing Class PasswordlessAuthBackend inside yourapp folder
'yourapp.auth_backend.PasswordlessAuthBackend',
]
因此,由于这里的文档,我解决了自己的问题:https://docs.djangoproject.com/en/2.1/topics/auth/customizing/
我所要做的就是在的auth_backend.py中验证函数
def authenticate(self, username=None):
至
def authenticate(self, request, username=None):
在文档中,它说你也可以更改类delcaration,使其不包括ModelBackend,但无论哪种方式都有效。