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 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都有現成的庫:
- django-ldap
-
flask-ldap
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

