没有密码的身份验证 Django

正如标题所述,我正在尝试验证没有密码的用户。我已经使用过这个:django authentication without a password来解决我的应用程序(在 Django 2.0 上)的问题,但我想在另一个应用程序中做同样的事情,但它在 Django 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

在 settings.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)

它永远不会达到我的自定义身份验证方法。任何和所有的帮助表示赞赏!


幕布斯6054654
浏览 158回答 3
3回答

慕工程0101907

所以我通过这里的文件解决了我自己的问题:https ://docs.djangoproject.com/en/2.1/topics/auth/customizing/我所要做的就是 auth_backend.py 中的 authetnicate 函数def authenticate(self, username=None):至def authenticate(self, request, username=None):在文档中它说您还可以将类声明更改为不包含 ModelBackend,但它可以以任何方式工作。

尚方宝剑之说

您可以尝试避免使用默认后端吗?改变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', ]

FFIVE

您在 settings.py 中的身份验证后端路径无效yourapp.auth_backend.YourAuth应该yourapp.auth_backend.PasswordlessAuthBackend
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python