使用MS Graph Python API获取令牌时遇证书过期错误求助
获取Graph API客户端令牌时的SSL证书验证错误
问题背景
正在学习微软官方《使用Graph API构建Python应用》教程,尝试获取客户端令牌时,出现“login.microsoftonline.com证书已过期”的错误,浏览器访问该网址正常。
测试代码
"""Simple test script to obtain app-only security token from Azure AD""" import configparser from msal import ConfidentialClientApplication # get credentials from config file config = configparser.ConfigParser() config.read(["config.cfg"]) CONFIG = config["azure"] SCOPE = 'https://graph.microsoft.com/.default' # Initialize ConfidentialClientApplication app = ConfidentialClientApplication( client_id=CONFIG["clientId"], client_credential=CONFIG["clientSecret"], authority=f"https://login.microsoftonline.com/{CONFIG['tenantId']}" ) # Acquire a token result = app.acquire_token_for_client(scopes=[SCOPE]) access_token = result['access_token'] print("Access Token:", access_token)
报错信息
ClientSecretCredential.get_token failed: Cannot connect to host login.microsoftonline.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:997)')]
更新尝试
添加verify=False参数后,错误转为警告,但该做法存在安全风险,不清楚如何适配msal库实现正确的证书验证:
app = ConfidentialClientApplication( client_id=CONFIG["clientId"], client_credential=CONFIG["clientSecret"], authority=f"https://login.microsoftonline.com/{CONFIG['tenantId']}", verify=False, )
警告信息:
InsecureRequestWarning: Unverified HTTPS request is being made to host 'login.microsoftonline.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings
解决方案
1. 更新本地CA证书库
Python依赖CA证书验证SSL证书有效性,可能是本地证书库过期导致问题:
- Windows:通过系统设置更新根证书
- Linux:执行
sudo apt update && sudo apt install --reinstall ca-certificates(Debian/Ubuntu系列)或对应发行版的证书更新命令 - macOS:打开钥匙串访问更新系统根证书;或执行
pip install --upgrade certifi更新Python使用的certifi证书包
2. 手动指定CA证书路径
如果系统证书无法正常更新,可下载login.microsoftonline.com对应的根证书,在初始化时指定证书路径:
app = ConfidentialClientApplication( client_id=CONFIG["clientId"], client_credential=CONFIG["clientSecret"], authority=f"https://login.microsoftonline.com/{CONFIG['tenantId']}", verify="/path/to/your/root_certificate.crt" # 替换为实际证书路径 )
3. 排查代理/防火墙干扰
部分代理或防火墙会替换SSL证书,导致验证失败。尝试关闭代理、切换网络环境(如手机热点)测试,确认是否为网络拦截导致的问题。
内容的提问来源于stack exchange,提问作者EmRa
相关产品推荐
相关产品推荐

