Django 中集成Microsoft 的AD 验证

 最近在django的项目中需要集成Microsoft的AD(Active Directory)验证系统,在网上google了一番之后,发现都是在谈论django如何与Openldap集成,没有找到与AD集成相关的例子。仔细看看后,本质上AD与Openldap应该没有什么太大的区别,都是ldap协议的具体实现,经过一番折腾后,终于可以工作了,先记录如下:

1. 当然需要先安装相关的软件包 ldap 和django_auth_ldap

2. 在settings.py中加入以下设置:

 1 import ldap 
 2 from django_auth_ldap.config import LDAPSearch,PosixGroupType,ActiveDirectoryGroupType 
 3 
 4 AUTH_LDAP_SERVER_URI = 'ldap://test.domain.com:389'
 5 AUTH_LDAP_BIND_DN = 'testuser'
 6 AUTH_LDAP_BIND_PASSWORD = 'password'
 7 AUTH_LDAP_USER_SEARCH = LDAPSearch('dc=test,dc=domain,dc=com', ldap.SCOPE_SUBTREE, '(sAMAccountName=%(user)s)',)
 8 AUTH_LDAP_GROUP_SEARCH = LDAPSearch('OU=GlobalUsers,DC=test,DC=domain,DC=com', ldap.SCOPE_SUBTREE, '(objectClass=group)')
 9 AUTH_LDAP_GROUP_TYPE = ActiveDirectoryGroupType()
10 
11 # Only users in this group can log in.
12 #AUTH_LDAP_REQUIRE_GROUP = 'DC=test,DC=domain,DC=com'
13 
14 # Populate the Django user from the LDAP directory.
15 AUTH_LDAP_USER_ATTR_MAP = {
16     'first_name': 'givenName',
17     'last_name': 'sn',
18     'email': 'mail'
19 }
20 
21 #AUTH_LDAP_PROFILE_ATTR_MAP = {
22 #    "employee_number": "employeeNumber"
23 #}
24 
25 AUTH_LDAP_USER_FLAGS_BY_GROUP = {
26     'is_active': 'cn=active,OU=GlobalUsers,DC=test,DC=domain,DC=com',
27     'is_staff': 'cn=staff,OU=GlobalUsers,DC=test,DC=domain,DC=com',
28     'is_superuser': 'cn=superuser,OU=GlobalUsers,DC=test,DC=domain,DC=com'
29 }
30 
31 # This is the default
32 AUTH_LDAP_ALWAYS_UPDATE_USER = False
33 
34 # Use LDAP group membership to calculate group permissions.
35 AUTH_LDAP_FIND_GROUP_PERMS = True
36 
37 # Cache group memberships for 5 minutes to reduce LDAP traffic
38 AUTH_LDAP_CACHE_GROUPS = True
39 AUTH_LDAP_GROUP_CACHE_TIMEOUT = 300
40 AUTH_LDAP_GLOBAL_OPTIONS = {
41     ldap.OPT_X_TLS_REQUIRE_CERT: False,
42     ldap.OPT_REFERRALS: False,
43 }
44 
45 # Keep ModexampleBackend around for per-user permissions and maybe a local superuser.
46 AUTHENTICATION_BACKENDS = (
47     'django_auth_ldap.backend.LDAPBackend',
48     'django.contrib.auth.backends.ModelBackend', 
49 )                                                                         
在实验阶段,发现加入以下代码到settings.py中,用来做调试,挺有用的,大家可以试试。
1 import logging
2 logger = logging.getLogger('django_auth_ldap')
3 logger.addHandler(logging.StreamHandler())
4 logger.setLevel(logging.DEBUG)

 

posted @ 2012-10-09 15:21  沙发上的懒猫  阅读(2167)  评论(0编辑  收藏  举报