|
| 1 | +# coding: utf-8 |
| 2 | + |
| 3 | +# ------------------------------------------------------------------------- |
| 4 | +# Copyright (c) Microsoft Corporation. All rights reserved. |
| 5 | +# Licensed under the MIT License. See License.txt in the project root for |
| 6 | +# license information. |
| 7 | +# -------------------------------------------------------------------------- |
| 8 | + |
| 9 | +""" |
| 10 | +Example: Using truststore.SSLContext with Azure SDK for Python (Sync and Async) |
| 11 | +
|
| 12 | +This sample demonstrates how to use `truststore.SSLContext` directly to leverage |
| 13 | +operating system certificate stores when working with Azure SDK for Python. |
| 14 | +
|
| 15 | +Unlike `truststore.inject_into_ssl()` which globally patches the ssl module, |
| 16 | +this approach gives you more control over which connections use system certificates |
| 17 | +by creating custom transport sessions with a truststore-based SSLContext. |
| 18 | +
|
| 19 | +Requirements: |
| 20 | + pip install truststore azure-identity azure-storage-blob aiohttp requests |
| 21 | +USAGE: |
| 22 | + python example_truststore_ssl_context.py |
| 23 | +""" |
| 24 | + |
| 25 | +import ssl |
| 26 | +import asyncio |
| 27 | +import truststore |
| 28 | +import requests |
| 29 | +import aiohttp |
| 30 | +from requests.adapters import HTTPAdapter |
| 31 | + |
| 32 | +from azure.identity import DefaultAzureCredential |
| 33 | +from azure.identity.aio import DefaultAzureCredential as AsyncDefaultAzureCredential |
| 34 | +from azure.storage.blob import BlobServiceClient |
| 35 | +from azure.storage.blob.aio import BlobServiceClient as AsyncBlobServiceClient |
| 36 | +from azure.core.pipeline.transport import RequestsTransport, AioHttpTransport |
| 37 | + |
| 38 | + |
| 39 | +# ============================================================================= |
| 40 | +# Helper: Custom HTTPAdapter for requests |
| 41 | +# ============================================================================= |
| 42 | + |
| 43 | + |
| 44 | +class TruststoreHTTPAdapter(HTTPAdapter): |
| 45 | + """Custom HTTPAdapter that uses truststore.SSLContext for SSL verification.""" |
| 46 | + |
| 47 | + def __init__(self, ssl_context, **kwargs): |
| 48 | + self._ssl_context = ssl_context |
| 49 | + super().__init__(**kwargs) |
| 50 | + |
| 51 | + def init_poolmanager(self, *args, **kwargs): |
| 52 | + kwargs["ssl_context"] = self._ssl_context |
| 53 | + return super().init_poolmanager(*args, **kwargs) |
| 54 | + |
| 55 | + |
| 56 | +# ============================================================================= |
| 57 | +# Synchronous Example |
| 58 | +# ============================================================================= |
| 59 | + |
| 60 | + |
| 61 | +def sync_blob_storage_with_ssl_context(): |
| 62 | + """Synchronous Azure Blob Storage using truststore.SSLContext directly. |
| 63 | +
|
| 64 | + This approach gives you more control over the SSL context configuration |
| 65 | + without globally injecting truststore into ssl module. |
| 66 | + """ |
| 67 | + |
| 68 | + account_url = "https://<your-storage-account>.blob.core.windows.net" |
| 69 | + |
| 70 | + # Create SSLContext using truststore (uses system certificate stores) |
| 71 | + ssl_context = truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 72 | + |
| 73 | + # Create a session with truststore adapter |
| 74 | + session = requests.Session() |
| 75 | + adapter = TruststoreHTTPAdapter(ssl_context) |
| 76 | + session.mount("https://", adapter) |
| 77 | + |
| 78 | + # Create transport with the custom session |
| 79 | + transport = RequestsTransport(session=session, session_owner=False) |
| 80 | + |
| 81 | + with transport: |
| 82 | + credential = DefaultAzureCredential() |
| 83 | + blob_service_client = BlobServiceClient( |
| 84 | + account_url=account_url, |
| 85 | + credential=credential, |
| 86 | + transport=transport, |
| 87 | + ) |
| 88 | + |
| 89 | + print("=== Sync Blob Storage with SSLContext ===") |
| 90 | + for container in blob_service_client.list_containers(): |
| 91 | + print(f"Container: {container['name']}") |
| 92 | + |
| 93 | + blob_service_client.close() |
| 94 | + credential.close() |
| 95 | + |
| 96 | + session.close() # Close the session manually since session_owner=False |
| 97 | + |
| 98 | + |
| 99 | +# ============================================================================= |
| 100 | +# Asynchronous Example |
| 101 | +# ============================================================================= |
| 102 | + |
| 103 | + |
| 104 | +async def async_blob_storage_with_ssl_context(): |
| 105 | + """Asynchronous Azure Blob Storage using truststore.SSLContext directly. |
| 106 | +
|
| 107 | + This approach gives you more control over the SSL context configuration |
| 108 | + without globally injecting truststore into ssl module. |
| 109 | + """ |
| 110 | + |
| 111 | + account_url = "https://<your-storage-account>.blob.core.windows.net" |
| 112 | + |
| 113 | + # Create SSLContext using truststore (uses system certificate stores) |
| 114 | + ssl_context = truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 115 | + |
| 116 | + # Create a TCPConnector with our truststore SSLContext |
| 117 | + connector = aiohttp.TCPConnector(ssl=ssl_context) |
| 118 | + session = aiohttp.ClientSession(connector=connector) |
| 119 | + |
| 120 | + # Create transport with the custom session |
| 121 | + transport = AioHttpTransport(session=session, session_owner=False) |
| 122 | + |
| 123 | + async with transport: |
| 124 | + credential = AsyncDefaultAzureCredential() |
| 125 | + blob_service_client = AsyncBlobServiceClient( |
| 126 | + account_url=account_url, |
| 127 | + credential=credential, |
| 128 | + transport=transport, |
| 129 | + ) |
| 130 | + |
| 131 | + print("=== Async Blob Storage with SSLContext ===") |
| 132 | + async for container in blob_service_client.list_containers(): |
| 133 | + print(f"Container: {container['name']}") |
| 134 | + |
| 135 | + await blob_service_client.close() |
| 136 | + await credential.close() |
| 137 | + |
| 138 | + await session.close() # Close the session manually since session_owner=False |
| 139 | + |
| 140 | + |
| 141 | +if __name__ == "__main__": |
| 142 | + sync_blob_storage_with_ssl_context() |
| 143 | + asyncio.run(async_blob_storage_with_ssl_context()) |
0 commit comments