首页 文章

自定义电子邮件身份验证后端在django 2.1.4中不起作用

提问于
浏览
0

我在 django 2.1.4 中集成自定义身份验证后端时遇到问题 . 以下是我的代码:
我的 FMS.authBackend 模块:

from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend

class authEmailBackend(ModelBackend):
    def authenticate(self, username=None, password=None, **kwargs):
        print("aaaaaaa")
        UserModel = get_user_model()
        try:
            user = UserModel.objects.get(email=username)
        except UserModel.DoesNotExist:
            return None
        else:
            if user.check_password(password):
                return user
        return None

我的 settings.py

AUTHENTICATION_BACKENDS = (
                'FMS.authBackend.authEmailBackend',
                'django.contrib.auth.backends.ModelBackend',

                )

我的 urls.py

from django.contrib.auth import views as auth_views
urlpatterns = [ 
        path('login', my_decos.logout_required(auth_views.LoginView.as_view(template_name = 'register/login.html')),name = 'login')
]

上面的代码在我的情况下不起作用 . authEmailBackend 中的函数 authenticate 永远不会被调用为在控制台中打印,但我在 authenticate 函数中打印语句 .

虽然相同的代码适用于 django 2.0.8 ,但唯一的区别是 urls.py 是:

from django.contrib.auth import views as auth_views
urlpatterns = [ 
        path('login', my_decos.logout_required(auth_views.login(template_name = 'register/login.html')),name = 'login')
]

但是在较新的django中, django.contrib.auth.views.login 不再支持,我们需要使用 django.contrib.auth.views.LoginView . 我在某处读到了使用自定义 AUTHENTICATION_BACKEND 我们的url必须指向 django.contrib.auth.views.login 但这在这里是不可能的 .

那么请你帮我解决这个问题 .

1 回答

  • 0

    request参数需要传递给authenticate方法

    class authEmailBackend(ModelBackend):
            **def authenticate(self, request, username=None, password=None, **kwargs):**
                print("aaaaaaa")
                UserModel = get_user_model()
                try:
                    user = UserModel.objects.get(email=username)
                except UserModel.DoesNotExist:
                    return None
                else:
                    if user.check_password(password):
                        return user
                return None
    

相关问题