Python使用LDAP作用戶認證

LDAP(Light Directory Access Portocol)是輕量目錄訪問協議,基於X.500標準,支持TCP/IP。html

LDAP目錄以樹狀的層次結構來存儲數據。每一個目錄記錄都有標識名(Distinguished Name,簡稱DN),用來讀取單個記錄,通常是這樣的:python

cn=username,ou=people,dc=test,dc=com

幾個關鍵字的含義以下:git

  •  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。github

python-ldap

python通常使用python-ldap庫操做ldap,文檔:https://www.python-ldap.org/en/latest/index.htmldjango

下載:flask

pip install python-ldap

還要安裝一些環境,ubuntu:ubuntu

apt-get install build-essential python3-dev python2.7-dev \
    libldap2-dev libsasl2-dev slapd ldap-utils python-tox \
    lcov valgrind

CentOS:python2.7

yum groupinstall "Development tools"
yum install openldap-devel python-devel

 獲取LDAP地址後便可與LDAP創建鏈接:ui

import ldap
ldapconn = ldap.initialize('ldap://192.168.1.111:389')

 綁定用戶,可用於用戶驗證,用戶名必須是dn:spa

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

相關文章
相關標籤/搜索