简体   繁体   English

如何通过 OpenLdap 使用 Python ldap3 验证用户和密码?

[英]How can I verify user and password using Python ldap3 via OpenLdap?

For a django project, I designed a different login page.对于一个 django 项目,我设计了一个不同的登录页面。 The users here will log in via openldap.这里的用户将通过 openldap 登录。

I can access users' full information with their uid id, but I could not find how to verify the password.我可以使用用户的 uid id 访问用户的完整信息,但我找不到如何验证密码。

Do I need to hash the user's password and compare it with the password on ldap?我是否需要散列用户的密码并将其与 ldap 上的密码进行比较? Isn't there any other method?没有其他方法吗? Thank you谢谢

from ldap3 import Server, Connection, ALL, SUBTREE
from ldap3.core.exceptions import LDAPException, LDAPBindError, LDAPSocketOpenError
from ldap3.utils.conv import escape_filter_chars

ldap_server_uri=f"ldap://xxx:389"
ldap_base = 'dc=xx,dc=xx,dc=xx'

def ldap(uid,password):
    try:     
        ldap_server = Server(ldap_server_uri, get_info=ALL)
        ldap_connection = Connection(ldap_server, user = 'uid=admin,ou=xx,dc=xx,dc=xx',password='adminpassword')
        if ldap_connection.bind() == True:
            if ldap_connection.search(search_base=ldap_base, search_filter=f'(uid={uid})',search_scope = SUBTREE, attributes=['uid']) == True:
                ent = ldap_connection.entries[0]
                entry = {'uid': ent['uid']}
                ldap_connection.unbind()
                return entry
            else:
                return None
    except LDAPSocketOpenError:
        print('Unabled to connect to the LDAP server!')
        return None

Just to check the username and password I use:只是为了检查我使用的用户名和密码:

import ldap3
from ldap3.core.exceptions import LDAPException


def _ldap_login(username, password):
    try:
        with ldap3.Connection('enter_server', user=username, password=password) as conn:
            print(conn.result["description"]) # "success" if bind is ok
            return True
    except LDAPException:
        print('Unable to connect to LDAP server')
        return False

_ldap_login("enter_username", "enter_password")

The following are 30 code examples for showing how to use ldap3 and Tutorial: Introduction to ldap3 .以下是30 个代码示例,用于展示如何使用ldap3教程:ldap3 简介

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM