python-ldap: 检查密码与Microsoft AD时应该使用什么编码?

1 投票
1 回答
1570 浏览
提问于 2025-04-18 16:58

我有一个django应用程序,为它写了一个叫做ActiveDirectoryAuthBackend的东西,参考了这个代码片段(它使用了python-ldap库)。

大部分时候它运行得很好。

不过,有些用户的域密码里包含非ASCII字符,这就导致认证失败,因为在simple_bind_s(username, password)这个函数中,编码转换出现了问题。

其实,django传递的密码值是一个unicode字符串。所以我想我需要在把这个unicode传给simple_bind_s之前先进行编码,这样就能避免默认的编码转换失败。

但我不知道该用什么编码。密码服务器是微软的Active Directory。

有什么建议吗?

谢谢。

O.

1 个回答

2

经过一些测试和阅读用户包含非ASCII字符的内容后,我发现我这个域名最可能使用的编码是“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

撰写回答