You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求Google OAuth访问令牌时遇SSL证书验证失败求解决方案

解决Python请求Google OAuth2 Token时的"unable to get local issuer certificate"错误

问题背景

使用Python请求https://accounts.google.com/o/oauth2/token获取access token时触发SSL证书验证失败,但curl可正常访问该接口且证书显示受信任,核心报错为:

ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)

这是因为Python的证书存储与系统/curl使用的证书存储不一致导致的。

解决建议

1. 运行Python官方安装包的证书配置脚本

针对macOS上的官方Python(路径为/Library/Frameworks/Python.framework/Versions/3.12),直接执行安装目录下的证书配置脚本:

/Library/Frameworks/Python.framework/Versions/3.12/Install Certificates.command

该脚本会自动安装certifi库并配置Python使用完整的根证书链,修复证书信任问题。

2. 手动指定CA证书路径

如果脚本执行无效,可以手动指定curl使用的系统CA证书路径(macOS常见路径为/etc/ssl/cert.pem或/usr/local/etc/openssl/cert.pem):

  • 使用urllib时:
    import ssl
    import urllib.request
    
    ssl_context = ssl.create_default_context(cafile='/etc/ssl/cert.pem')
    # 替换为你的请求逻辑
    with urllib.request.urlopen('https://accounts.google.com/o/oauth2/token', context=ssl_context) as response:
        response_data = response.read()
    
  • 使用requests库时:
    import requests
    
    # 替换为你的请求参数
    response = requests.post('https://accounts.google.com/o/oauth2/token', verify='/etc/ssl/cert.pem')
    

3. 配置环境变量指定证书文件

设置SSL_CERT_FILE环境变量指向系统CA证书,让Python全局使用该证书:

  • 终端临时设置:
    export SSL_CERT_FILE=/etc/ssl/cert.pem
    
    之后再运行Python脚本。
  • 脚本内设置:
    import os
    os.environ['SSL_CERT_FILE'] = '/etc/ssl/cert.pem'
    

4. 更新certifi库

如果你的Python依赖certifi(比如requests默认依赖),更新到最新版本以获取完整的根证书链:

pip install --upgrade certifi

内容的提问来源于stack exchange,提问作者DraftDodger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 14:02:21