1. 程式人生 > 實用技巧 >Django+ldap認證示例

Django+ldap認證示例

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