Python ldap3 错误: [SSL: CERTIFICATE_VERIFY_FAILED] 证书验证失败:无法获取本地颁发者证书 (_ssl.c:1006)

0 投票
1 回答
71 浏览
提问于 2025-04-14 15:54

我正在尝试在Mac M1上使用ldap3库从Python框架连接到ldap服务器。

from ldap3 import Server, Connection, SUBTREE, ALL, Tls, MODIFY_REPLACE
from fastapi import FastAPI
from typing import Union
from pydantic import BaseModel
import ssl

app = FastAPI()

tls_configuration = Tls(validate=ssl.CERT_REQUIRED,version=ssl.PROTOCOL_TLSv1_2,ca_certs_file="./app/client_cert.pem")
server = Server("ldaps://ldaps.adserver.com",port=636,use_ssl=True,tls=tls_configuration, get_info=ALL)
conn = Connection(server, user='mydomain.com\user', password='DemoPass%',auto_bind=True,authentication="NTLM")
print(f"Connection: {conn}")

我使用下面的命令提取了证书,并将--Begin Certificate--到--End Certificate--的内容保存为.pem格式的文件,放在应用程序文件夹里。

openssl s_client -connect ldaps.adserver.com:636

在测试连接时,我仍然收到证书无效的错误。

Traceback (most recent call last):
  File "/Users/demo/Documents/GitHub/project/app/main.py", line 13, in <module>
    conn = Connection(server, user='domain\user', password='DemoPass%',auto_bind=True,authentication="NTLM")
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/demo/anaconda3/lib/python3.11/site-packages/ldap3/core/connection.py", line 363, in __init__
    self._do_auto_bind()
  File "/Users/demo/anaconda3/lib/python3.11/site-packages/ldap3/core/connection.py", line 387, in _do_auto_bind
    self.open(read_server_info=False)
  File "/Users/demo/anaconda3/lib/python3.11/site-packages/ldap3/strategy/sync.py", line 57, in open
    BaseStrategy.open(self, reset_usage, read_server_info)
  File "/Users/demo/anaconda3/lib/python3.11/site-packages/ldap3/strategy/base.py", line 146, in open
    raise exception_history[0][0]
ldap3.core.exceptions.LDAPSocketOpenError: ("('socket ssl wrapping error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1006)',)",)

我该如何验证我创建的.pem文件是否有效,以及如何在Python的ldap3中使用它。

1 个回答

0

这个错误主要是说发行者有问题,而不是证书本身。你需要获取发行者的证书(可能是中间证书或根证书),如果这些证书不在你的信任存储中,你需要把所有的证书都拿到,直到根证书为止。

请把pem文件改名为cer文件,然后在Windows上双击打开。你会在“详细信息”标签里看到“发行者”这一项,你需要从LDAP服务器提供商那里获取那个发行者的证书。你可能需要一个包含所有证书链的单一文件。然后这些证书需要安装在你的代码运行的信任存储中。当代码运行时,你可以在事件查看器的CAPI2日志中追踪这些证书链验证事件,路径是:应用程序和服务 - Microsoft - Windows - CAPI2 - 操作。首先,你需要启用日志记录,这样日志可能会很快填满。

撰写回答