Python连接Azure存储账户AAD认证时遇SSL证书验证失败问题
解决Azure存储AAD认证SSL证书验证失败问题
针对你遇到的azure.core.exceptions.ClientAuthenticationError: Authentication failed: [SSL: CERTIFICATE_VERIFY_FAILED]错误,结合你已安装certifi的情况,可以通过以下几种方式在代码中配置证书路径:
方法1:代码内设置环境变量
Azure SDK底层依赖的HTTP库(如requests、urllib3)会读取REQUESTS_CA_BUNDLE或SSL_CERT_FILE环境变量加载自定义证书。在代码开头添加以下配置:
import os import certifi # 指定certifi证书路径 os.environ['REQUESTS_CA_BUNDLE'] = certifi.where() os.environ['SSL_CERT_FILE'] = certifi.where()
此配置会让SDK在发起认证和存储请求时自动使用certifi提供的证书文件。
方法2:为ClientSecretCredential配置自定义传输层
如果环境变量方式不生效,可以为ClientSecretCredential指定带有证书配置的HTTP传输对象,确保认证请求使用正确的证书:
from azure.storage.blob import BlobServiceClient from azure.identity import ClientSecretCredential from azure.core.pipeline.transport import RequestsTransport import certifi import os AzureFileName = 'myfile.gzip' LocalFilePath = 'c:\\myfile.gzip' container_name = 'AContainer' blob_path = f'test1/{AzureFileName}' # 创建带证书验证的传输对象 transport = RequestsTransport(verify=certifi.where()) # 初始化凭证时绑定传输对象 csCred = ClientSecretCredential( 'theTenant', 'theClientID', 'theSecret', transport=transport ) account_url = "https://mystorage.blob.core.windows.net" try: blob_service_client = BlobServiceClient(account_url=account_url, credential=csCred) print(f'The Full Azure path is {account_url}/{container_name}/{blob_path}') blobClient = blob_service_client.get_blob_client(container=container_name, blob=blob_path) print('Writing local file to Azure...') with open(LocalFilePath, 'rb') as data: blobClient.upload_blob(data, overwrite=True, connection_timeout=14400) print('Done') except Exception as ex: print(ex) raise
额外修正:容器与Blob路径的错误
你当前代码中get_blob_client的container参数传入了完整URL路径(AzureFilePath),这是错误用法。正确逻辑是:
container参数仅传入容器名称(如AContainer)blob参数传入容器内的文件相对路径(如test1/myfile.gzip)
上述修正后的代码已调整此逻辑,避免后续出现路径相关错误。
内容的提问来源于stack exchange,提问作者lem
相关产品推荐
相关产品推荐

