Microsoft-Graph:无法从 python 代码获取令牌:错误 SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED]

Microsoft-Graph: Failing to get token from python code: Error SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED]

我需要调用一个网络API。为此,我需要一个不记名令牌。

我正在使用 databricks(python) 代码首先通过 Microsoft AAD 进行身份验证。然后为我的 service_user 获取不记名令牌。我遵循了微软文档 docs

但在访问我们公司服务器并要求 SSL 证书时遇到问题。

我无法安装任何证书。有什么更好的方法可以避免它。下面是我从上面的微软和 Git 回购中获取的简短代码。但它不起作用。

我能得到帮助吗?

clientId = "42xx-xx-xx5f"
authority = "https://login.microsoftonline.com/tenant_id/"
app = msal.PublicClientApplication(client_id=clientId, authority=authority)
user = "serviceuser@company.com"
pwd = "password"
scope = "Directory.Read.All"

result = app.acquire_token_by_username_password(scopes=[scope], username=user, password=pwd)
print(result)

低于错误

HTTPSConnectionPool(host='mycompany.com', port=443): Max retries exceeded with url: /adfs/services/trust/mex (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1125)')))

谢谢Indranil。将您的建议作为答案发布以帮助其他社区成员。

建议在您组织的环境中使用verify = False,因为它会禁用 SSL 验证。

有时,当您使用公司代理时,它会将证书链替换为 Proxy 的证书链。在 certifi 使用的 cacert.pem 中添加证书应该可以解决问题。

  1. 找到cacert.pem所在的路径:

    安装 certifi,如果你没有。命令:pip install certifi

    import certifi
    certifi.where()
    C:\Users\[UserID]\AppData\Local\Programs\Python\Python37-32\lib\site-packages\certifi\cacert.pem```
    
    
  2. 在浏览器上打开 URL。从 URL 下载 certificates 的链并保存为 Base64 encoded .cer 文件。

  3. 现在在记事本中打开cacert.pem并在末尾添加每个下载的证书内容(---Begin Certificate--- *** ---End Certificate---)。

可以参考, SSL: CERTIFICATE_VERIFY_FAILED and

问题是代码使用依赖于 certifi 包的 requests 库而不是使用 Linux 证书链(因此 existing instructions doesn't work). To solve that problem it's better to use cluster init script 将安装 SSL certificate when cluster starts. Something like this (requests and certifi are installed by default), just replace CERT_FILE with actual path to the .pem file with CA 证书:

CERT_FILE="/dbfs/....."
CERTIFI_HOME="$(python -m certifi 2>/dev/null)"
cat $CERT_FILE >> $CERTIFI_HOME