【问题标题】:Django Authentication on different databases不同数据库上的 Django 身份验证
【发布时间】:2019-03-21 00:32:35
【问题描述】:
我想为客户创建一个应用程序,其中每个客户都有自己的数据库。因此作为登录信息,他们需要输入三个不同的字段:客户编号、用户名、密码。
用户名和密码应该做正常的身份验证工作,并且 customernumber 在那里可以转到正确的数据库用户表进行身份验证我可以通过 using() 方法转到其他数据库但是如何通过正确的身份验证用户数据库?
【问题讨论】:
标签:
django
authentication
multiple-databases
【解决方案1】:
您应该像下面那样编写自定义身份验证后端,并且必须使用 AUTHENTICATION_BACKENDS 键在 settings.py 中指定。 Django doc
from django.contrib.auth.backends import ModelBackend
class CustomAuthBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
user = User.objects.using(request.GET['CUSTOMER_TABLE']).filter(username=username)
if user.check_password(password) and self.user_can_authenticate(user):
return user