Python3.6实现ldap的登录验证

python3通过ldap3库来处理ldap。至于怎么安装ldap3,就不作赘述了。

查过很多资料也看过官网文档,可能英文的还是没看透彻,解决问题后再去看官网,竟然透彻了很多,走过很多弯路,现在将解决方法加代码解说一下。

1.先附一下我用到的ldap结构图,个人根据自己的结构或属性不同,可对应更改相应字段。

Python3.6实现ldap的登录验证_第1张图片

如图所示,我的 ldap的基本搜索入口就是 'dc=***,dc=com',也就是你用管理员登录时需要写的入口(小铺垫,后面你普通用户和密码时也得有对应的搜索地址)。也可以看到ldap的加密方式是SSHA方式,当然这种方式,在后面也可以通过代码查询提现出来。在网上搜的很多方法是已经查询出密码,难点在于将我们手动输入的密码转化为SSHA加密或将查询的密码解密然后进行判断。这种方式我试过很多,结果都不对。然后又搜资料发现,只要正确输入对应的用户和密码,只要搜索入口对的话,Connection又bind后,有返回值就说明了是否用户名和密码是对的。话不多说,直接上代码。

from ldap3 import Server, Connection, SUBTREE, ALL

ldap_host = '你的地址'
ldap_port = 389
ldap_admin_user = '你的admin'
ldap_admin_password = '你的admin密码'
ldap_base_search = 'dc=***,dc=com'

def ldap_auth(username,password):
    s = Server(host=ldap_host, port=ldap_port, use_ssl=False, get_info='ALL')
    #这个首先看看你的admin能不能正常connect
    ldapz_admin_connection = Connection(s, user=ldap_admin_user, password=ldap_admin_password, auto_bind='NONE', version=3,
                             authentication='SIMPLE', client_strategy='SYNC', auto_referrals=True, check_names=True,
                             read_only=False, lazy=False,
                             raise_exceptions=False)
    #连上以后必须bind才能有值
    ldapz_admin_connection.bind()
    
    #这个是为了查询你输入的用户名的入口搜索地址
    res = ldapz_admin_connection.search(search_base=ldap_base_search,
                         search_filter='(uid={})'.format(username),
                         search_scope=SUBTREE,
                         attributes=['cn','uid','userPassword'])   #这里可能由你自己选择

    if res:
        entry = ldapz_admin_connection.response[0]
        dn = entry['dn']
        attr_dict = entry['attributes']
        print(attr_dict)

        try:
            #这个connect是通过你的用户名和密码还有上面搜到的入口搜索来查询的
            conn2 = Connection(s, user=dn, password=password, check_names=True, lazy=False, raise_exceptions=False)
            conn2.bind()
            print(conn2.result["description"])
            #正确-success 不正确-invalidCredentials
            if conn2.result["description"] == "success":
                print("yes")
            else:
                print("no")
        except Exception as e:
            print("no1")
            print(e)

ldap_auth("你的用户名","你的密码")

功德无量的事儿!感谢,点赞吧!

你可能感兴趣的:(程序开发)