本文为Django 2.1 通过LDAP 调用 FreeIPA账户信息 例子。
FreeIPA 的搭建,可以参考我上一篇博客
http://blog.51cto.com/hequan/2164114
测试环境记得修改 django运行环境的 /etc/hosts文件 Freeipa ip 域名
软件版本:
Django==2.1
django-auth-ldap==1.7.0
django-cors-headers==2.4.0
djangorestframework==3.8.2
pyasn1==0.4.4
pyasn1-modules==0.2.2
python-ldap==3.1.0
pytz==2018.5
项目名字 stack
├── db.sqlite3
├── manage.py
├── requirements.txt
└── stack
├── __init__.py
├── ldapconfig.py
├── settings.py
├── urls.py
└── wsgi.py
ldapconfig.py
# https://github.com/django-auth-ldap/django-auth-ldap
# FreeIPA 域名 server.zhuxu.co
import ldap
from django_auth_ldap.config import LDAPSearch, LDAPSearchUnion, GroupOfNamesType
AUTHENTICATION_BACKENDS = (
'django_auth_ldap.backend.LDAPBackend',
'django.contrib.auth.backends.ModelBackend',
)
AUTH_LDAP_SERVER_URI = 'ldap://192.168.100.23'
AUTH_LDAP_BIND_DN = 'uid=admin,cn=users,cn=accounts,dc=zhuxu,dc=co'
AUTH_LDAP_BIND_PASSWORD = '123456'
AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr="cn") # 返回的组的类型,并用来判断用户与组的从属关系
AUTH_LDAP_USER_SEARCH = LDAPSearch("cn=accounts,dc=zhuxu,dc=co", ldap.SCOPE_SUBTREE, "(uid=%(user)s)")
AUTH_LDAP_GROUP_SEARCH = LDAPSearch("dc=zhuxu,dc=co", ldap.SCOPE_SUBTREE,"(objectClass=groupofnames)")
AUTH_LDAP_USER_ATTR_MAP = {
"username": "uid",
"password": "userPassword",
"first_name": "givenName",
"last_name": "sn",
"email": "mail",
}
AUTH_LDAP_ALWAYS_UPDATE_USER = True # 是否同步LDAP修改
AUTH_LDAP_MIRROR_GROUPS = True # 导入用户的组信息,在用户登录的时候把用户的域组关系同步过来。每次用户登录时,都会把用户的组关系删除,重新从ldap中进行同步
AUTH_LDAP_FIND_GROUP_PERMS = True # 使用LDAP组成员计算组权限。
AUTHENTICATION_BACKENDS = (
'django_auth_ldap.backend.LDAPBackend',
'django.contrib.auth.backends.ModelBackend',
)
AUTH_LDAP_CACHE_TIMEOUT = 3600
settings.py
from .ldapconfig import *
常规设置 REST_FRAMEWORK
url.py
from django.contrib import admin
from django.urls import path
from rest_framework.authtoken import views
urlpatterns = [
path('', admin.site.urls),
path('token/', views.obtain_auth_token),
]