Skip to content

Commit a69a3c2

Browse files
authored
add example to demo how to use truststore (#44343)
* add example to demo how to use truststore * add sslcontext examples * update readme * update * update * run black
1 parent 84ed92a commit a69a3c2

3 files changed

Lines changed: 240 additions & 2 deletions

File tree

‎sdk/core/azure-core/samples/README.md‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,5 +22,10 @@ They are not intended to be run as standalone application, but show you how thes
2222

2323
These are some code snippets that show the way in which end users can customize the behavior.
2424

25-
[shared_transport.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core/samples/example_shared_transport.py) - samples of how to use a shared sync transport
26-
[shared_transport_async.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core/samples/example_shared_transport_async.py) - samples of how to use a shared async transport
25+
[example_shared_transport.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core/samples/example_shared_transport.py) - samples of how to use a shared sync transport
26+
27+
[example_shared_transport_async.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core/samples/example_shared_transport_async.py) - samples of how to use a shared async transport
28+
29+
[example_truststore_injection.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core/samples/example_truststore_injection.py) - samples of how to use the `truststore` library to leverage OS certificate stores via global injection
30+
31+
[example_truststore_ssl_context.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core/samples/example_truststore_ssl_context.py) - samples of how to use `truststore.SSLContext` directly with custom transport sessions
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
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 with Azure SDK for Python (Sync and Async)
11+
12+
This sample demonstrates how to use the `truststore` library to leverage
13+
operating system certificate stores when working with Azure SDK for Python,
14+
including both synchronous (requests) and asynchronous (aiohttp)
15+
HTTP clients.
16+
17+
Requirements:
18+
pip install truststore azure-identity azure-storage-blob aiohttp
19+
USAGE:
20+
python example_truststore_injection.py
21+
"""
22+
23+
import asyncio
24+
import truststore
25+
26+
# Inject truststore BEFORE importing Azure SDK libraries
27+
truststore.inject_into_ssl()
28+
29+
# Synchronous imports
30+
from azure.identity import DefaultAzureCredential
31+
from azure.storage.blob import BlobServiceClient
32+
33+
# Asynchronous imports
34+
from azure.identity.aio import DefaultAzureCredential as AsyncDefaultAzureCredential
35+
from azure.storage.blob.aio import BlobServiceClient as AsyncBlobServiceClient
36+
37+
38+
# =============================================================================
39+
# Synchronous Example
40+
# =============================================================================
41+
42+
43+
def sync_blob_storage_example():
44+
"""Synchronous Azure Blob Storage with system certificates."""
45+
46+
account_url = "https://<your-storage-account>.blob.core.windows.net"
47+
48+
credential = DefaultAzureCredential()
49+
blob_service_client = BlobServiceClient(account_url=account_url, credential=credential)
50+
51+
print("=== Sync Blob Storage ===")
52+
for container in blob_service_client.list_containers():
53+
print(f"Container: {container['name']}")
54+
55+
blob_service_client.close()
56+
credential.close()
57+
58+
59+
# =============================================================================
60+
# Asynchronous Example (uses aiohttp underneath)
61+
# =============================================================================
62+
63+
64+
async def async_blob_storage_example():
65+
"""Asynchronous Azure Blob Storage with system certificates (aiohttp)."""
66+
67+
account_url = "https://<your-storage-account>.blob.core.windows.net"
68+
69+
# Async credential and client - aiohttp will use the injected truststore
70+
credential = AsyncDefaultAzureCredential()
71+
blob_service_client = AsyncBlobServiceClient(account_url=account_url, credential=credential)
72+
73+
print("=== Async Blob Storage ===")
74+
async for container in blob_service_client.list_containers():
75+
print(f"Container: {container['name']}")
76+
77+
# Always close async clients
78+
await blob_service_client.close()
79+
await credential.close()
80+
81+
82+
async def main():
83+
# Run async example
84+
await async_blob_storage_example()
85+
86+
87+
if __name__ == "__main__":
88+
sync_blob_storage_example()
89+
asyncio.run(main())
90+
truststore.extract_from_ssl()
Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
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

Comments
 (0)