0
# Azure Platform Credentials
1
2
Leverage Azure's native authentication mechanisms for secure, credential-free authentication within Azure environments. These credentials provide automatic authentication for Azure-hosted applications without requiring stored secrets or user interaction.
3
4
## Capabilities
5
6
### ManagedIdentityCredential
7
8
Authenticates using Azure Managed Identity, providing automatic authentication for Azure services including Virtual Machines, App Service, Function Apps, Azure Container Instances, and Azure Kubernetes Service. Eliminates the need to store credentials in application code.
9
10
```python { .api }
11
class ManagedIdentityCredential:
12
def __init__(
13
self,
14
*,
15
client_id: Optional[str] = None,
16
identity_config: Optional[Mapping[str, str]] = None,
17
**kwargs
18
):
19
"""
20
Create a ManagedIdentityCredential for Azure managed identity authentication.
21
22
Args:
23
client_id: User-assigned managed identity's client ID. If not specified, uses system-assigned identity.
24
identity_config: Configuration for user-assigned identity. Use either:
25
- {"client_id": "client-id-value"} for user-assigned identity by client ID
26
- {"object_id": "object-id-value"} for user-assigned identity by object ID
27
- {"mi_res_id": "resource-id-value"} for user-assigned identity by Azure resource ID
28
29
Note:
30
- System-assigned identity: Available automatically on supported Azure services
31
- User-assigned identity: Must be created and assigned to the Azure resource
32
- Only specify client_id OR identity_config, not both
33
"""
34
35
def get_token(self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs) -> AccessToken:
36
"""
37
Request an access token using managed identity.
38
39
Args:
40
*scopes: Desired scopes for the access token
41
claims: Additional claims required in the token (not supported for managed identity)
42
tenant_id: Optional tenant ID override (not supported for managed identity)
43
44
Returns:
45
AccessToken: The access token with expiration information
46
47
Raises:
48
CredentialUnavailableError: Managed identity is not available on this platform
49
ClientAuthenticationError: Failed to authenticate with managed identity service
50
"""
51
52
def get_token_info(self, *scopes: str, options: Optional[dict] = None) -> dict:
53
"""
54
Request access token with additional information.
55
56
Args:
57
*scopes: Desired scopes for the access token
58
options: Additional options for token acquisition
59
60
Returns:
61
dict: Token information including access token and metadata
62
"""
63
```
64
65
**Usage Examples:**
66
67
```python
68
from azure.identity import ManagedIdentityCredential
69
70
# System-assigned managed identity (default)
71
credential = ManagedIdentityCredential()
72
73
# User-assigned managed identity by client ID
74
user_assigned_credential = ManagedIdentityCredential(
75
client_id="your-user-assigned-identity-client-id"
76
)
77
78
# User-assigned managed identity by object ID
79
object_id_credential = ManagedIdentityCredential(
80
identity_config={"object_id": "your-identity-object-id"}
81
)
82
83
# User-assigned managed identity by Azure resource ID
84
resource_id_credential = ManagedIdentityCredential(
85
identity_config={"mi_res_id": "/subscriptions/{sub}/resourcegroups/{rg}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{name}"}
86
)
87
88
# Use with Azure SDK
89
from azure.storage.blob import BlobServiceClient
90
91
blob_client = BlobServiceClient(
92
account_url="https://account.blob.core.windows.net",
93
credential=credential
94
)
95
96
# Virtual Machine authentication example
97
from azure.keyvault.secrets import SecretClient
98
99
# This automatically works on Azure VMs with managed identity enabled
100
secret_client = SecretClient(
101
vault_url="https://vault.vault.azure.net/",
102
credential=ManagedIdentityCredential()
103
)
104
105
secret = secret_client.get_secret("database-connection-string")
106
```
107
108
### WorkloadIdentityCredential
109
110
Authenticates using Azure workload identity for Kubernetes workloads. Enables pods running in Azure Kubernetes Service (AKS) to authenticate using Kubernetes service account tokens federated with Azure Active Directory.
111
112
```python { .api }
113
class WorkloadIdentityCredential:
114
def __init__(
115
self,
116
*,
117
tenant_id: Optional[str] = None,
118
client_id: Optional[str] = None,
119
token_file_path: Optional[str] = None,
120
authority: Optional[str] = None,
121
**kwargs
122
):
123
"""
124
Create a WorkloadIdentityCredential for Kubernetes workload identity authentication.
125
126
Args:
127
tenant_id: ID of the application's Microsoft Entra tenant (defaults to AZURE_TENANT_ID env var)
128
client_id: The application's client ID (defaults to AZURE_CLIENT_ID env var)
129
token_file_path: Path to JWT token file (defaults to AZURE_FEDERATED_TOKEN_FILE env var)
130
authority: Authority of a Microsoft Entra endpoint
131
132
Environment Variables:
133
AZURE_TENANT_ID: Microsoft Entra tenant ID
134
AZURE_CLIENT_ID: Azure AD application client ID
135
AZURE_FEDERATED_TOKEN_FILE: Path to Kubernetes service account token file
136
137
Note:
138
Typically used in Azure Kubernetes Service (AKS) pods with workload identity enabled.
139
The token file is automatically mounted by the workload identity webhook.
140
"""
141
142
def get_token(self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs) -> AccessToken:
143
"""
144
Request an access token using workload identity.
145
146
Args:
147
*scopes: Desired scopes for the access token
148
claims: Additional claims required in the token
149
tenant_id: Optional tenant ID override
150
151
Returns:
152
AccessToken: The access token with expiration information
153
154
Raises:
155
CredentialUnavailableError: Required environment variables or token file not available
156
"""
157
158
def get_token_info(self, *scopes: str, options: Optional[dict] = None) -> dict:
159
"""
160
Request access token with additional information.
161
162
Args:
163
*scopes: Desired scopes for the access token
164
options: Additional options for token acquisition
165
166
Returns:
167
dict: Token information including access token and metadata
168
"""
169
```
170
171
**Usage Example:**
172
173
```python
174
from azure.identity import WorkloadIdentityCredential
175
176
# Workload identity (automatically configured in AKS pods)
177
credential = WorkloadIdentityCredential()
178
179
# Explicit configuration
180
explicit_credential = WorkloadIdentityCredential(
181
tenant_id="your-tenant-id",
182
client_id="your-client-id",
183
token_file_path="/var/run/secrets/azure/tokens/azure-identity-token"
184
)
185
186
# Use in Kubernetes pod
187
from azure.keyvault.secrets import SecretClient
188
189
# This works automatically in AKS pods with workload identity
190
secret_client = SecretClient(
191
vault_url="https://vault.vault.azure.net/",
192
credential=WorkloadIdentityCredential()
193
)
194
```
195
196
### AzurePipelinesCredential
197
198
Authenticates using Azure Pipelines service connections for secure authentication within Azure DevOps pipelines without exposing credentials in pipeline definitions.
199
200
```python { .api }
201
class AzurePipelinesCredential:
202
def __init__(
203
self,
204
*,
205
system_access_token: str,
206
service_connection_id: str,
207
tenant_id: Optional[str] = None,
208
**kwargs
209
):
210
"""
211
Create an AzurePipelinesCredential for Azure Pipelines authentication.
212
213
Args:
214
system_access_token: The System.AccessToken value from Azure Pipelines
215
service_connection_id: The service connection ID for the Azure Resource Manager connection
216
tenant_id: ID of the application's Microsoft Entra tenant (optional)
217
218
Note:
219
This credential exchanges the Azure Pipelines system access token for an Azure AD token
220
using the specified service connection. The service connection must be configured in
221
Azure DevOps with appropriate permissions.
222
"""
223
224
def get_token(self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs) -> AccessToken:
225
"""
226
Request an access token using Azure Pipelines service connection.
227
228
Args:
229
*scopes: Desired scopes for the access token
230
claims: Additional claims required in the token
231
tenant_id: Optional tenant ID override
232
233
Returns:
234
AccessToken: The access token with expiration information
235
236
Raises:
237
CredentialUnavailableError: Not running in Azure Pipelines or invalid service connection
238
"""
239
240
def get_token_info(self, *scopes: str, options: Optional[dict] = None) -> dict:
241
"""
242
Request access token with additional information.
243
244
Args:
245
*scopes: Desired scopes for the access token
246
options: Additional options for token acquisition
247
248
Returns:
249
dict: Token information including access token and metadata
250
"""
251
```
252
253
**Usage Example:**
254
255
```python
256
# In Azure Pipelines YAML
257
# - task: PythonScript@0
258
# env:
259
# SYSTEM_ACCESSTOKEN: $(System.AccessToken)
260
261
import os
262
from azure.identity import AzurePipelinesCredential
263
264
# Use in Azure Pipelines
265
credential = AzurePipelinesCredential(
266
system_access_token=os.environ["SYSTEM_ACCESSTOKEN"],
267
service_connection_id="your-service-connection-id"
268
)
269
270
# Deploy to Azure from pipeline
271
from azure.mgmt.resource import ResourceManagementClient
272
273
resource_client = ResourceManagementClient(
274
credential=credential,
275
subscription_id="your-subscription-id"
276
)
277
```
278
279
## Platform-Specific Credentials
280
281
The following credentials are used internally by Azure services and typically not used directly in application code:
282
283
### Service Fabric Credential
284
285
```python { .api }
286
# Internal use - Service Fabric Mesh applications
287
class ServiceFabricCredential:
288
"""Authenticates using Service Fabric managed identity (internal use)."""
289
```
290
291
### App Service Credential
292
293
```python { .api }
294
# Internal use - Azure App Service applications
295
class AppServiceCredential:
296
"""Authenticates using App Service managed identity (internal use)."""
297
```
298
299
### Azure Arc Credential
300
301
```python { .api }
302
# Internal use - Azure Arc enabled servers
303
class AzureArcCredential:
304
"""Authenticates using Azure Arc managed identity (internal use)."""
305
```
306
307
### Azure ML Credential
308
309
```python { .api }
310
# Internal use - Azure Machine Learning compute
311
class AzureMLCredential:
312
"""Authenticates using Azure ML managed identity (internal use)."""
313
```
314
315
### Cloud Shell Credential
316
317
```python { .api }
318
# Internal use - Azure Cloud Shell
319
class CloudShellCredential:
320
"""Authenticates using Azure Cloud Shell managed identity (internal use)."""
321
```
322
323
### IMDS Credential
324
325
```python { .api }
326
# Internal use - Azure Instance Metadata Service
327
class ImdsCredential:
328
"""Authenticates using Azure IMDS managed identity endpoint (internal use)."""
329
```
330
331
## Azure Environment Support
332
333
### Supported Azure Services
334
335
**Virtual Machines:**
336
- System-assigned managed identity: Enabled in VM settings
337
- User-assigned managed identity: Assigned to VM
338
339
**App Service & Function Apps:**
340
- System-assigned managed identity: Enabled in Identity settings
341
- User-assigned managed identity: Assigned in Identity settings
342
343
**Azure Container Instances:**
344
- User-assigned managed identity: Specified during container creation
345
346
**Azure Kubernetes Service:**
347
- Workload identity: Pods with federated service accounts
348
- Managed identity: Node pools with managed identity
349
350
**Azure Container Apps:**
351
- System-assigned managed identity: Enabled in Identity settings
352
- User-assigned managed identity: Assigned in Identity settings
353
354
**Azure Logic Apps:**
355
- System-assigned managed identity: Enabled automatically
356
- User-assigned managed identity: Assigned in Identity settings
357
358
### Azure Cloud Support
359
360
```python { .api }
361
# Public cloud (default)
362
credential = ManagedIdentityCredential()
363
364
# Azure Government
365
gov_credential = WorkloadIdentityCredential(
366
authority="https://login.microsoftonline.us"
367
)
368
369
# Azure China
370
china_credential = WorkloadIdentityCredential(
371
authority="https://login.chinacloudapi.cn"
372
)
373
```
374
375
## Best Practices
376
377
### Managed Identity Recommendations
378
379
1. **Prefer system-assigned identity** for single-service scenarios
380
2. **Use user-assigned identity** for multi-service or complex scenarios
381
3. **Grant minimum required permissions** using Azure RBAC
382
4. **Monitor identity usage** with Azure Monitor and Activity Log
383
5. **Test authentication** in both development and production environments
384
385
### Workload Identity Setup
386
387
```bash
388
# Enable workload identity on AKS cluster
389
az aks update \
390
--resource-group myResourceGroup \
391
--name myAKSCluster \
392
--enable-workload-identity
393
394
# Create user-assigned managed identity
395
az identity create \
396
--resource-group myResourceGroup \
397
--name myUserAssignedIdentity
398
399
# Create Kubernetes service account with federation
400
az aks get-credentials --resource-group myResourceGroup --name myAKSCluster
401
402
kubectl create serviceaccount workload-identity-sa
403
404
# Establish federated credential
405
az identity federated-credential create \
406
--name myFederatedIdentity \
407
--identity-name myUserAssignedIdentity \
408
--resource-group myResourceGroup \
409
--issuer $(az aks show --resource-group myResourceGroup --name myAKSCluster --query "oidcIssuerProfile.issuerUrl" -o tsv) \
410
--subject system:serviceaccount:default:workload-identity-sa
411
```
412
413
### Pod Configuration for Workload Identity
414
415
```yaml
416
# Kubernetes deployment with workload identity
417
apiVersion: apps/v1
418
kind: Deployment
419
metadata:
420
name: workload-identity-app
421
spec:
422
template:
423
metadata:
424
labels:
425
azure.workload.identity/use: "true"
426
spec:
427
serviceAccountName: workload-identity-sa
428
containers:
429
- name: app
430
image: myapp:latest
431
env:
432
- name: AZURE_CLIENT_ID
433
value: "your-client-id"
434
- name: AZURE_TENANT_ID
435
value: "your-tenant-id"
436
```
437
438
### Error Handling and Diagnostics
439
440
```python
441
from azure.identity import ManagedIdentityCredential, CredentialUnavailableError
442
from azure.core.exceptions import ClientAuthenticationError
443
import logging
444
445
# Enable detailed logging
446
logging.basicConfig(level=logging.DEBUG)
447
448
try:
449
credential = ManagedIdentityCredential()
450
token = credential.get_token("https://management.azure.com/.default")
451
print("Managed identity authentication successful")
452
453
except CredentialUnavailableError as e:
454
print(f"Managed identity not available: {e}")
455
# Fallback to other authentication method
456
457
except ClientAuthenticationError as e:
458
print(f"Authentication failed: {e}")
459
# Check managed identity configuration and permissions
460
```