【问题标题】:How to call the authenticate() method of Custom written AuthenticationBackend of django in views.py?如何在views.py中调用django自定义编写的AuthenticationBackend的authenticate()方法?
【发布时间】:2020-02-08 12:27:13
【问题描述】:

我正在开发一个 Django 项目,在该项目中我定义了一个自定义用户模型,我需要为其编写自定义身份验证方法,按照我编写的文档,如下所示但是我在调​​用它时遇到问题views.py 请通过查看以下代码来帮助我
我已将我的自定义后端定义如下
我的自定义身份验证后端

from django.contrib.auth.backends import BaseBackend
from .models import User
from IntellerMatrix.CommonUtilities.constants import Constants


class AuthenticationBackend(BaseBackend):
    """
    Authentication Backend
    :To manage the authentication process of user
    """

    def authenticate(self, email=None, password=None):
        user = User.objects.get(email=email)
        if user is not None and user.check_password(password):
            if user.is_active == Constants.YES:
                return user
            else:
                return "User is not activated"
        else:
            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 = ['Modules.users.authentication.AuthenticationBackend',
                           'django.contrib.auth.backends.ModelBackend', ]

Views.py

def login(request):
    email = 'ialihaider75@gmail.com'
    password = 'ali'
    user = # how to call here that custom authentication backend's authenticate method

    if user is None:
        return HttpResponse("<p>Not Valid</p>")
    else:
        return HttpResponse(user)

【问题讨论】:

    标签: python django django-authentication custom-authentication


    【解决方案1】:

    您可以拨打authenticate(..) function [Django-doc]

    使用authenticate() 验证一组凭据。它将凭据作为关键字参数,usernamepassword 用于默认情况,针对每个身份验证后端检查它们,如果凭据对后端有效,则返回 User 对象。所以:

    from django.contrib.auth import authenticate
    
    def login(request):
        email = 'ialihaider75@gmail.com'
        password = 'ali'
        user = authenticate(request, email=email, password=password)
    
        if user is None:
            return HttpResponse('<p>Not Valid</p>')
        else:
            return HttpResponse(user)

    请注意,您实现的身份验证方法可以返回字符串。正如documentation on writing an authentication backend 所说:

    (…)

    无论哪种方式,authenticate() 都应该检查它获得的凭据,如果凭据有效,则返回与这些凭据匹配的用户对象。如果它们无效,应该返回None

    class AuthenticationBackend(BaseBackend):
        """
        Authentication Backend
        :To manage the authentication process of user
        """
    
        def authenticate(self, request, email=None, password=None):
            try:
                user = User.objects.get(email=email)
            except User.DoesNotExist:
                return None
            if user is not None and user.check_password(password):
                if user.is_active == Constants.YES:
                    return user
            return None

    此外,这会记录您的使用,这只是检查凭据是否有效。所以要登录用户还是需要拨打login(..) function [Django-doc]

    【讨论】:

    • authenticate() 方法来自哪个库我的意思是我必须导入上面提到的调用 authenticate() 的内容。
    • @IPFlashorAli:如顶行所示:from django.contrib.auth import authenticate
    • 好的,我已经调用了它,但是我的身份验证方法失败了。
    • 我认为我的自定义方法没有调用,而是 Django 总是调用其默认的 authenticate() 方法
    • @IPFlashorAli:正如文档指定的那样:它将遍历后端并调用它们。但是,您忘记添加 request 参数,因此这可能是它失败的原因。我建议仔细阅读文档,并尊重条件,否则它确实可能不起作用。请注意,您需要将参数(emailpassword)作为 named 参数传递。
    【解决方案2】:

    与其直接调用 Backend 类的 authenticate() 方法,不如使用 authenticate() 函数:

    user = authenticate(email=email, password=password)
    

    这更通用,并使您的代码更灵活。由于您可能有不同的身份验证后端,它们接受不同的参数,例如令牌。因此,无需导入所有后端并尝试每个后端,您只需将所需的参数传递给 authenticate 函数,这将自动调用每个身份验证后端。

    【讨论】:

      猜你喜欢
      • 2016-06-12
      • 2015-10-29
      • 2018-08-20
      • 2016-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-25
      相关资源
      最近更新 更多