通过AD / LDAP进行身份验证

时间:2017-11-15 10:45:09

标签: python active-directory ldap3

我对AD和LDAP了解不多,但尝试在Python中实现最简单的LDAP / AD登录功能。到目前为止,虽然我测试了几个不同的模块最有希望的可能是ldap3

>>> import ldap3
>>> server = ldap3.Server('myserver')
>>> connection = ldap3.Connection(server)
>>> connection.bind()
True
>>> connection.search(search_base='DC=mydomain,DC=com', search_filter='(&(objectClass=person)(userPrincipalName=firstname.lastname@mydomain.com))', search_scope='LEVEL', attributes=ldap3.ALL_ATTRIBUTES)
True
>>> connection.response[0]
{'uri': ['ldap://ForestDnsZones.mydomain.com/DC=ForestDnsZones,DC=mydomain,DC=com??base'], 'type': 'searchResRef'}
>>> connection.result
{'result': 0, 'description': 'success', 'dn': '', 'message': '', 'referrals': None, 'type': 'searchResDone'}

如果这是在正确的道路上,你能给我一些指示吗?

对于基础知识来说,设置似乎已经足够了,因为我能够从中提取某些类型的元数据:

>>> server._get_dsa_info(connection)
>>> server._dsa_info
DSA info (from DSE):
  Supported LDAP versions: 3, 2
  Naming contexts:
    DC=mydomain,DC=com
    CN=Configuration,DC=mydomain,DC=com
    CN=Schema,CN=Configuration,DC=mydomain,DC=com
    DC=DomainDnsZones,DC=mydomain,DC=com
    DC=ForestDnsZones,DC=mydomain,DC=com

  Supported controls:
    1.2.840.113556.1.4.1338 - Verify name - Control - MICROSOFT
    1.2.840.113556.1.4.1339 - Domain scope - Control - MICROSOFT
    1.2.840.113556.1.4.1340 - Search options - Control - MICROSOFT
    ...

我也试过flask-ldap3-login,但是我开始怀疑我的AD没有按照标准配置,因为我得到了:

...
>>> response = ldap_manager.authenticate('me', 'my_pass')
LDAPNoSuchObjectResult - 32 - noSuchObject - CN=Schema,CN=Configuration,DC=mydomain,DC=com - 0000208D: NameErr: DSID-0315270B, problem 2001 (NO_OBJECT), data 0, best match of:
        'CN=Schema,CN=Configuration,DC=mydomain,DC=com'
  - searchResDone - None

请不要犹豫,要求提供更多信息,我会尽力把它弄清楚。例如,我自己的用户位于:

CN=Lastname Firstname,OU=Consultants,OU=Users,OU=SE,OU=MYDOMAIN,DC=mydomain,DC=com

有些值是:

objectClass = top;person;organizationalPerson;user
name = Lastname Firstname
userPrincipalName = Firstname.Lastname@mydomain.com

此外,从CN=Schema,CN=Configuration,DC=mydomain,DC=com只有一个子模式,即CN=Aggregate,CN=Schema,CN=Configuration,DC=mydomain,DC=com,它看起来是空的。出于某种原因,我相信这就是flask-ldap3-login尝试使用的内容。

1 个答案:

答案 0 :(得分:1)

我使用import ldap3 user = 'me@mycompany.com' password = 'mypassword' server = ldap3.Server('myserver') connection = ldap3.Connection(server, user=user, password=password) connection.bind() connection.search(search_base='DC=mycompany,DC=com', search_filter='(&(objectClass=user)(userPrincipalName='+user+'))', search_scope='SUBTREE', attributes='*') 的问题是我在绑定时没有使用登录。这似乎是一种前进的方式:

attrs = connection.response[0]['attributes']
print(attrs['displayName'])
for memb in attrs['memberOf']:
    print(memb.partition('=')[2].partition(',')[0])

如果你想打印一些数据:

<br>