【问题标题】:Search and get a list of matching LDAP users in Django在 Django 中搜索并获取匹配的 LDAP 用户列表
【发布时间】:2013-09-24 15:17:03
【问题描述】:

我使用django-auth-ldap 作为我的后端来验证我的 LDAP 目录。我所有的配置都在settings.py 中,我能够毫无问题地验证自己。

但是,我不知道如何搜索 LDAP 目录并获取与输入字段中输入的前几个字符匹配的用户列表。

我不想在视图中重复自己。我想基本上做类似user_list = LDAPBackend().search(term) 的事情,其中​​术语是在页面上的输入字段中输入的字符串。然后,我将 user_list 的 JSON 转储返回到页面以填充页面上的下拉列表。

这是我已有的代码 sn-ps:

通过 Ajax 将输入的字符发送到 Django 视图:

JS 加载到 $(document).ready():

$("input#people").autocomplete({
                source: "{% url 'people_search' %}",
                minLength: 3,
                select: function (event, ui) {
                    //process selected user
                }
            });

在 Django 视图中接收输入的文本:

def people_search(request):
    term = request.GET.get('term') # term => text sent from the page
    user_list = []
    user_list = LDAPBackend().search(term) # search does not exist. I need to populate this array with all users that match the captured term.
    return HttpResponse(json.dumps(user_list))

settings.py:

# LDAP Authentication
import ldap
from django_auth_ldap.config import LDAPSearch, NestedGroupOfNamesType

AUTH_LDAP_SERVER_URI = 'ldap://mydomain.com:3268'
AUTH_LDAP_BIND_DN = 'my_uname'
AUTH_LDAP_BIND_PASSWORD = 'my_pass'
AUTH_LDAP_USER_SEARCH = LDAPSearch("DC=site,DC=domain,DC=com", ldap.SCOPE_SUBTREE, "(&(objectClass=*)(sAMAccountName=%(user)s))")
AUTH_LDAP_GROUP_SEARCH = LDAPSearch("DC=site,DC=domain,DC=com", ldap.SCOPE_SUBTREE, "(objectClass=group)")
AUTH_LDAP_GROUP_TYPE = NestedGroupOfNamesType()

AUTH_LDAP_CONNECTION_OPTIONS = {
    ldap.OPT_DEBUG_LEVEL: 0,
    ldap.OPT_REFERRALS: 0,
}

AUTH_LDAP_USER_ATTR_MAP = {
    "first_name": "givenName",
    "last_name": "sn",
    "email": "mail",
}

AUTH_LDAP_PROFILE_ATTR_MAP = {
    "employee_id": "employeeID",
}


AUTH_LDAP_ALWAYS_UPDATE_USER = True
AUTH_LDAP_FIND_GROUP_PERMS = True

注意:视图people_search@login_required 装饰。如果我没有通过身份验证,我将被重定向到登录页面,我可以在该页面成功执行user = LDAPBackend().authenticate(username=username, password=password)

我在 settings.py 中看到了AUTH_LDAP_USER_SEARCH,但我不确定如何使用它。文档并没有真正帮助我。

另外,理想情况下,我希望尽可能快地进行搜索。在 Microsoft Outlook 中,我能够快速搜索 LDAP 目录。我相信所有用户在我的电脑上都是cached。我可以将所有用户缓存在我的 Django 服务器上。

感谢您的帮助。

【问题讨论】:

  • @shailenTH 你找到解决办法了吗?
  • @Prats 不幸的是,我不能再回答这个问题了。我现在不再做 Django 了。我希望您找到解决方案,将其发布在这里,我可以将其标记为已接受的答案:)

标签: python django search active-directory ldap


【解决方案1】:

要在对象名称未知但对象名称中的某些字符已知的情况下搜索对象,请使用尽可能低的搜索范围并使用子字符串过滤器。下面的过滤器是一个子字符串过滤器:

(cn=shail*)

另见

【讨论】:

  • 链接都死了(截至2015/05/17),答案甚至没有解决用户的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-11
  • 1970-01-01
  • 2014-07-11
  • 2014-07-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多