(编辑:jimmy 日期: 2024/11/16 浏览:2)
LDAP(Light Directory Access Portocol)是轻量目录访问协议,基于X.500标准,支持TCP/IP。
LDAP目录以树状的层次结构来存储数据。每个目录记录都有标识名(Distinguished Name,简称DN),用来读取单个记录,
一般是这样的:
cn=username,ou=people,dc=test,dc=com
几个关键字的含义如下:
所以上面的dn代表一条记录,代表一位在test.com公司people部门的用户username。
python-ldap
python一般使用python-ldap库操作ldap,文档:https://www.python-ldap.org/en/latest/index.html。
下载:
pip install python-ldap
还要安装一些环境,ubuntu:
apt-get install build-essential python3-dev python2.7-dev libldap2-dev libsasl2-dev slapd ldap-utils python-tox lcov valgrind
CentOS:
yum groupinstall "Development tools" yum install openldap-devel python-devel
获取LDAP地址后即可与LDAP建立连接:
import ldap ldapconn = ldap.initialize('ldap://192.168.1.111:389')
绑定用户,可用于用户验证,用户名必须是dn:
ldapconn.simple_bind_s('cn=username,ou=people,dc=test,dc=com', pwd)
成功认证时会返回一个tuple:
(97, [], 1, [])
验证失败会报异常ldap.INVALID_CREDENTIALS:
{'desc': u'Invalid credentials'}
注意验证时传空值验证也是可以通过的,注意要对dn和pwd进行检查。
查询LDAP用户信息时,需要登录管理员RootDN帐号:
ldapconn.simple_bind_s('cn=admin,dc=test,dc=com', 'adminpwd') searchScope = ldap.SCOPE_SUBTREE searchFilter = 'cn=username' base_dn = 'ou=people,dc=test,dc=com' print ldapconn.search_s(base_dn, searchScope, searchFilter, None)
添加用户add_s(dn, modlist),dn为要添加的条目dn,modlist为存储信息:
dn = 'cn=test,ou=people,dc=test,dc=com' modlist = [ ('objectclass', ['person', 'organizationalperson'], ('cn', ['test']), ('uid', [''testuid]), ('userpassword', ['pwd']), ] result = ldapconn.add_s(dn, modlist)
添加成功会返回元组:
(105, [], 2, [])
失败会报ldap.LDAPError异常
Django使用LDAP验证
一个很简单的LDAP验证Backend:
import ldap class LDAPBackend(object): """ Authenticates with ldap. """ _connection = None _connection_bound = False def authenticate(self, username=None, passwd=None, **kwargs): if not username or not passwd: return None if self._authenticate_user_dn(username, passwd): user = self._get_or_create_user(username, passwd) return user else: return None @property def connection(self): if not self._connection_bound: self._bind() return self._get_connection() def _bind(self): self._bind_as( LDAP_CONFIG['USERNAME'], LDAP_CONFIG['PASSWORD'], True ) def _bind_as(self, bind_dn, bind_password, sticky=False): self._get_connection().simple_bind_s( bind_dn, bind_password ) self._connection_bound = sticky def _get_connection(self): if not self._connection: self._connection = ldap.initialize(LDAP_CONFIG['HOST']) return self._connection def _authenticate_user_dn(self, username, passwd): bind_dn = 'cn=%s,%s' % (username, LDAP_CONFIG['BASE_DN']) try: self._bind_as(bind_dn, passwd, False) return True except ldap.INVALID_CREDENTIALS: return False def _get_or_create_user(self, username, passwd): # 获取或者新建User return user
不想自己写的话,django与flask都有现成的库:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。