settings.py 配置以下变量,参与AD认证
AUTH_LDAP_SERVER_URI = 'ldap://10.108.198.6:389' AUTH_LDAP_BIND_DN = 'CN=test,OU=Service Accounts,DC=lenovo,dc=com' AUTH_LDAP_BIND_PASSWORD = 'password' AUTH_LDAP_USER_SEARCH = LDAPSearch( base_dn='OU=User Accounts,DC=lenovo,DC=com', scope=ldap.SCOPE_SUBTREE, filterstr='(sAMAccountName=%(user)s)' ) AUTH_LDAP_USER_ATTR_MAP = { 'first_name': 'givenName', 'last_name': 'sn', 'username': 'sAMAccountName', 'email': 'mail', }
如果需要在ad认证完成后进行其它操作,可自定义认证模型,netops是应用名,在settings.py同级目录下创建backends.py,并在在settings.py中增加
AUTHENTICATION_BACKENDS = ( 'netops.backends.AuthLDAPBackendBackend', 'netops.backends.AuthModelBackend', )
backends.py 代码如下
import re from django_auth_ldap.backend import LDAPBackend, _LDAPUser from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import Group import logging class AuthLDAPBackendBackend(LDAPBackend): def authenticate_ldap_user(self, ldap_user, password): """ Returns an authenticated Django user or None. """ user = ldap_user.authenticate(password) if user: if not user.is_active or not user.is_staff: user.is_active = True user.is_staff = True user.save() try: pass # your code... except Exception as e: logging.error(e) return user def authenticate(self, request, username=None, password=None, **kwargs): if password or self.settings.PERMIT_EMPTY_PASSWORD: ldap_user = _LDAPUser(self, username=username.strip(), request=request) user = self.authenticate_ldap_user(ldap_user, password) else: logging.debug('Rejecting empty password for {}'.format(username)) user = None if user: # your code... pass return user class AuthModelBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): user = super(AuthModelBackend, self).authenticate(request, username, password, **kwargs) return user