Python使用LDAP做用户认证
LDAP(Light Directory Access Portocol)是輕量目錄訪問協議,基于X.500標準,支持TCP/IP。
LDAP目錄以樹狀的層次結構來存儲數據。每個目錄記錄都有標識名(Distinguished Name,簡稱DN),用來讀取單個記錄,一般是這樣的:
cn=username,ou=people,dc=test,dc=com幾個關鍵字的含義如下:
- ?base dn:LDAP目錄樹的最頂部,也就是樹的根,是上面的dc=test,dc=com部分,一般使用公司的域名,也可以寫做o=test.com,前者更靈活一些。
- dc::Domain Component,域名部分。
- ou:Organization Unit,組織單位,用于將數據區分開。
- cn:Common Name,一般使用用戶名。
- uid:用戶id,與cn的作用類似。
- sn:Surname, 姓。
- rdn:Relative dn,dn中與目錄樹的結構無關的部分,通常存在cn或者uid這個屬性里。
所以上面的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 valgrindCentOS:
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 ldapclass LDAPBackend(object):"""Authenticates with ldap."""_connection = None_connection_bound = Falsedef authenticate(self, username=None, passwd=None, **kwargs):if not username or not passwd:return Noneif self._authenticate_user_dn(username, passwd):user = self._get_or_create_user(username, passwd)return userelse:return None@propertydef 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 = stickydef _get_connection(self):if not self._connection:self._connection = ldap.initialize(LDAP_CONFIG['HOST'])return self._connectiondef _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 Trueexcept ldap.INVALID_CREDENTIALS:return Falsedef _get_or_create_user(self, username, passwd):# 獲取或者新建Userreturn user不想自己寫的話,django與flask都有現成的庫:
django-ldap
flask-ldap
轉載于:https://www.cnblogs.com/linxiyue/p/10250243.html
總結
以上是生活随笔為你收集整理的Python使用LDAP做用户认证的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《智能家居》培训第五天------201
- 下一篇: python测试testsuite使用命