【问题标题】:Authentication without a passwrod Django没有密码的身份验证 Django
【发布时间】:2020-08-22 21:11:23
【问题描述】:

正如标题所述,我正在尝试验证没有密码的用户。我已经使用了这个: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)

它从不符合我的自定义身份验证方法。感谢您提供任何和所有帮助!

【问题讨论】:

    标签: python django authentication django-authentication


    【解决方案1】:

    您在 settings.py 中的身份验证后端路径无效

    yourapp.auth_backend.YourAuth
    

    应该是

    yourapp.auth_backend.PasswordlessAuthBackend
    

    【讨论】:

    • 那是mb。我已经正确地掌握了它。只是搞砸了复制和粘贴
    【解决方案2】:

    您可以尝试避免使用默认后端吗?

    改变

    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', 
    ]
    

    【讨论】:

    • 我实际上解决了我的问题。我所要做的就是在我的身份验证函数中添加请求作为参数
    【解决方案3】:

    感谢这里的文档,我解决了自己的问题:https://docs.djangoproject.com/en/2.1/topics/auth/customizing/

    我所要做的就是在 auth_backend.py 中验证函数

    def authenticate(self, username=None):
    

    def authenticate(self, request, username=None):
    

    在文档中它说您还可以更改类声明以不包括 ModelBackend,但它可以两种方式工作。

    【讨论】:

      猜你喜欢
      • 2011-09-27
      • 2019-06-18
      • 2011-07-04
      • 2014-12-15
      • 2013-11-27
      • 1970-01-01
      • 2020-09-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多