使用django_auth_ldap来实现ldap和django自己的认证系统auth

下载插件 python-ldap和django_auth_ldap

配置settings.py

一些基本说明:

设置Ldap的host地址和指定端口号

AUTH_LDAP_SERVER_URI = "ldap://"  

如果Ldap不能匿名访问需设定好指定的id和密码 

AUTH_LDAP_BIND_DN = ""

AUTH_LDAP_BIND_PASSWORD = ""

如果上一步认证成功,则会在以下路径检索登录用户user,

user是登录页面传递进来的,如果在Ldap中有该用户,在匹配密码进行认证

认证成功后会把以下信息同步到auth自己的auth_user表中

AUTH_LDAP_USER_ATTR_MAP = {
"first_name": "givenName",
"last_name": "sn",
"email": "mail",
} 

INSTALLED_APPS = (
    'django.contrib.auth',     
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '', 'USER':'', 'PASSWORD':'', } } import ldap from django_auth_ldap.config import LDAPSearch, GroupOfNamesType # Baseline configuration. AUTH_LDAP_SERVER_URI = "ldap://" AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_REFERRALS: 0 } AUTH_LDAP_BIND_DN = "" AUTH_LDAP_BIND_PASSWORD = "" AUTH_LDAP_USER_SEARCH = LDAPSearch("OU=,OU=,DC=,DC=com", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)") # AUTH_LDAP_USER_DN_TEMPLATE = "sAMAccountName=%(user)s,OU=Employees,OU=Cisco Users,DC=cisco,DC=com" # Populate the Django user from the LDAP directory. AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail", } # This is the default, but I like to be explicit. AUTH_LDAP_ALWAYS_UPDATE_USER = True # Use LDAP group membership to calculate group permissions. AUTH_LDAP_FIND_GROUP_PERMS = True # Cache group memberships for an hour to minimize LDAP traffic AUTH_LDAP_CACHE_GROUPS = True AUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600 # Keep ModelBackend around for per-user permissions and maybe a local # superuser. AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', )