当前位置: 移动技术网 > IT编程>脚本编程>Python > 详解Django-auth-ldap 配置方法

详解Django-auth-ldap 配置方法

2019年05月24日  | 移动技术网IT编程  | 我要评论

yanjiang,法号怪哉,最近什么电影好看

使用场景

公司内部使用django作为后端服务框架的web服务,当需要使用公司内部搭建的ldap 或者 windows 的ad服务器作为web登录认证系统时,就需要这个django-auth-ldap第三方插件

插件介绍

django-auth-ldap是一个django身份验证后端,可以针对ldap服务进行身份验证。有许多丰富的配置选项可用于处理用户,组和权限,便于对页面和后台的控制 插件介绍地址:django-auth-ldap

安装方法

注意:需先正确安装python3环境、pip3 和 django环境

前提: 需要先安装python-ldap > = 3.0

第一步:安装django-auth-ldap

pip install django-auth-ldap

第二步:在setting.py中配置django-auth-ldap 模块

要在django项目中使用auth认证,请将django_auth_ldap.backend.ldapbackend添加 到authentication_backends。不要向installed_apps添加任何内容。 添加完效果如下:

authentication_backends = [

'django_auth_ldap.backend.ldapbackend' ,

]

第三步:在django项目的settings.py中配置如下代码:

#django-auth-ldap 配置部分
import ldap
from django_auth_ldap.config import ldapsearch,groupofnamestype
 
#修改django认证先走ldap,再走本地认证
authentication_backends = [
 'django_auth_ldap.backend.ldapbackend',
 'django.contrib.auth.backends.modelbackend',
]
 
#ldap的连接基础配置
auth_ldap_server_uri = "ldap://xxx.xxx.xxx.xxx:389" # ldap or ad 服务器地址
auth_ldap_bind_dn = "cn=administrator,cn=users,dc=test,dc=com" # 管理员的dn路径
auth_ldap_bind_password = 'testpassword' # 管理员密码
 
#允许认证用户的路径
auth_ldap_user_search = ldapsearch("ou=test,dc=test,dc=intra",
     ldap.scope_subtree, "(samaccountname=%(user)s)")
 
#通过组进行权限控制
auth_ldap_group_search = ldapsearch("ou=groups,ou=test,dc=test,dc=intra",
 ldap.scope_subtree, "(objectclass=groupofnames)"
)
 
auth_ldap_group_type = groupofnamestype()
 
#is_staff:这个组里的成员可以登录;is_superuser:组成员是django admin的超级管理员;is_active:组成员可以登录django admin后台,但是无权限查看后台内容
auth_ldap_user_flags_by_group = {
 "is_staff": "cn=test_users,ou=groups,ou=test,dc=test,dc=com",
 "is_superuser": "cn=test_users,ou=groups,ou=tset,dc=test,dc=com",
}
#通过组进行权限控制end
 
#如果ldap服务器是windows的ad,需要配置上如下选项
auth_ldap_connection_options = {
 ldap.opt_debug_level: 1,
 ldap.opt_referrals: 0,
}
 
#当ldap用户登录时,从ldap的用户属性对应写到django的user数据库,键为django的属性,值为ldap用户的属性
auth_ldap_user_attr_map = {
 "first_name": "givenname",
 "last_name": "sn",
 "email": "mail"
}
 
#如果为true,每次组成员都从ldap重新获取,保证组成员的实时性;反之会对组成员进行缓存,提升性能,但是降低实时性
# auth_ldap_find_group_perms = true

以上配置完毕后,登录服务器后台地址:http://serverurl:8080/admin 使用ldap or ad中指定的group里的用户进行登录认证。希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网