从Django中的外部Active Directory中提取数据

时间:2016-05-06 02:54:12

标签: python django active-directory ldap

我目前有一个使用MySQL后端的应用程序,我有一个客户端,其中包含存储在其上的用户的配置文件信息,但他们也有Active Directory,并想知道我是否可以从中提取信息以检索信息从那里获取特定的个人资料。我知道您可以为多个SQL数据库连接配置Django,或者将身份验证后端替换为Active Directory。

https://docs.djangoproject.com/en/1.9/topics/db/multi-db/

https://pythonhosted.org/django-auth-ldap/

但是我想知道我是否可以同时执行MySQL和Active Directory,或者我只是需要从外部连接到Active Directory并以这种方式检索信息?

这是否可行,如果是这样,哪种方法最适合接近它?

1 个答案:

答案 0 :(得分:1)

我和我管理的Django网站有类似的情况。这是我使用的Django App:

https://github.com/etianen/django-python3-ldap

它允许我将PostgreSQL用于我的数据库,并将我需要的用户元数据从Active Directory中提取出来并通过映射字段​​提取到用户记录中。这是我在几次错误开始后找到的最佳方法。

如果您只是想从Active Directory中提取数据而不是从Django用户那里提取数据,那么这里是我发现的包和代码示例:

Python 3包:git + https://github.com/rbarrois/python-ldap.git@py3

示例,您可以修改它以使用Django的ORM:

"""
This code provide an example of how to connect to LDAP (specifically, Active Directory)
using Python 3.

Requires python-ldap3, available via the following command:
pip install git+https://github.com/rbarrois/python-ldap.git@py3
"""

import ldap

LDAP_URI = 'ldap://ldap.server.com'
LDAP_DN = 'dc=server,dc=com'
LDAP_USERNAME = 'ldap_user@server.com'
LDAP_PASSWORD = ''
USER_NAME = 'username-to-test'
USER_IN_GROUP = 'CN=SomeGroup,DC=server,DC=com'
USER_NOT_IN_GROUP = 'CN=SomeGroupThatDoesNotExist,DC=server,DC=com'

try:
    # Connect to LDAP / Active Directory
    ldap_con = ldap.initialize(LDAP_URI)
    ldap_con.protocol_version = 3
    ldap_con.set_option(ldap.OPT_REFERRALS, 0)
    ldap_con.simple_bind_s(LDAP_USERNAME, LDAP_PASSWORD)

    # sAMAAccountName is Active Directory's 'username'
    user_filter='(&(objectCategory=person)(objectClass=user)(sAMAccountName=' + USER_NAME + '))'
    attrs = ['memberOf']

    # Perform the search.
    ldap_user = ldap_con.search_s(LDAP_DN, ldap.SCOPE_SUBTREE, user_filter, attrs)

    # Active Directory returns a list of byte literals. Convert them to strings in a more sensibly named list.
    ldap_groups = []
    for value in ldap_user[0][1]['memberOf']:
        ldap_groups.append(value.decode('utf-8'))

    # Print the LDAP groups the user above is a member of, one per line.
    for value in ldap_groups:
        print(value)

    # Perform check to see whether a user is in a group, or explicitly, a user it not in a group.
    if USER_IN_GROUP in ldap_groups:
         print(USER_NAME + " is a member of " + USER_IN_GROUP)
    else:
         print(USER_NAME + " is not a member of " + USER_IN_GROUP)

    if USER_NOT_IN_GROUP in ldap_groups:
         print(USER_NAME + " is a member of " + USER_NOT_IN_GROUP)
    else:
         print(USER_NAME + " is not a member of " + USER_NOT_IN_GROUP)

    # Unbind from LDAP / Active Directory.
    ldap_con.unbind()
except ldap.LDAPError:
    print(ldap.LDAPError)

使用LDAP包连接到Active Directory时,这两行是必不可少的:

ldap_con.protocol_version = 3
ldap_con.set_option(ldap.OPT_REFERRALS, 0)