我有一个 Django 应用程序,我为其编写了一个 ActiveDirectoryAuthBackend
,基于 this snippet (它使用 python-ldap)。
大多数时候它工作正常。
现在,某些用户的域密码中包含非 ASCII 字符,这会导致身份验证失败,因为 simple_bind_s(username,password)
函数中的编码强制出现问题。
实际上,django传递的密码值是unicode。所以我想我需要在将其传递给 simple_bind_s 之前对其进行编码,从而避免默认编码转换失败。
但我不知道要使用什么编码。密码服务器是 Microsoft Active Directory。
有什么想法吗?
干杯。
哦。
最佳答案
经过一些测试并读取包含非 ASCII 字符的用户 CN 后,我发现我的域最可能的编码是“latin-1”。
检查凭据的好方法如下:
class ActiveDirectoryAuthBackend(backends.ModelBackend):
def authenticate(self, username=None, password=''):
try:
from django.contrib.auth.model import User
user = User.objects.get(username=username):
except User.DoesNotExist:
return None
from django.conf import settings
import ldap
con = ldap.initialize('ldap://{0}'.format(settings.get('LDAP_SERVER', None)))
con.set_option(ldap.OPT_REFERRALS, 0)
try:
con.simple_bind_s(username, password.encode('latin1'))
return user
exceot ldap.INVALID_CREDENTIALS:
return None
关于python-ldap : what encoding should I use to check password against Microsoft AD?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25261306/