0
# Authentication and Configuration
1
2
Azure authentication patterns, client initialization options, and configuration management for optimal SDK usage across different Azure environments. This covers credential management, client configuration, and best practices for secure and efficient authorization management operations.
3
4
## Capabilities
5
6
### Client Initialization
7
8
Configure and initialize the AuthorizationManagementClient with appropriate credentials and settings.
9
10
```python { .api }
11
class AuthorizationManagementClient:
12
def __init__(
13
self,
14
credential: TokenCredential,
15
subscription_id: str,
16
api_version: Optional[str] = None,
17
base_url: str = "https://management.azure.com",
18
profile: KnownProfiles = KnownProfiles.default,
19
**kwargs
20
):
21
"""
22
Initialize the Azure Authorization Management client.
23
24
Parameters:
25
- credential: Azure credential object implementing TokenCredential interface
26
- subscription_id: Azure subscription ID for resource management
27
- api_version: Specific API version to use (optional, defaults to latest stable)
28
- base_url: Azure management endpoint URL
29
- profile: API version profile for operation groups
30
- kwargs: Additional configuration options
31
"""
32
33
def close(self) -> None:
34
"""Close the client and release resources."""
35
36
def __enter__(self):
37
"""Enter context manager."""
38
39
def __exit__(self, *exc_details):
40
"""Exit context manager and clean up resources."""
41
```
42
43
### Credential Management
44
45
Support for various Azure authentication methods and credential types.
46
47
```python { .api }
48
# DefaultAzureCredential - Recommended for most scenarios
49
from azure.identity import DefaultAzureCredential
50
51
credential = DefaultAzureCredential()
52
53
# ClientSecretCredential - For service principal authentication
54
from azure.identity import ClientSecretCredential
55
56
credential = ClientSecretCredential(
57
tenant_id="tenant-id",
58
client_id="client-id",
59
client_secret="client-secret"
60
)
61
62
# ManagedIdentityCredential - For Azure resources
63
from azure.identity import ManagedIdentityCredential
64
65
credential = ManagedIdentityCredential(client_id="managed-identity-client-id")
66
67
# InteractiveBrowserCredential - For interactive scenarios
68
from azure.identity import InteractiveBrowserCredential
69
70
credential = InteractiveBrowserCredential(tenant_id="tenant-id")
71
72
# AzureCliCredential - Using Azure CLI authentication
73
from azure.identity import AzureCliCredential
74
75
credential = AzureCliCredential()
76
```
77
78
### Configuration Options
79
80
Advanced client configuration for optimal performance and behavior customization.
81
82
```python { .api }
83
class AuthorizationManagementClientConfiguration:
84
def __init__(
85
self,
86
credential: TokenCredential,
87
subscription_id: str,
88
**kwargs
89
):
90
"""
91
Configuration for the AuthorizationManagementClient.
92
93
Parameters:
94
- credential: Azure credential
95
- subscription_id: Azure subscription ID
96
- kwargs: Additional configuration options including:
97
- polling_interval: Default polling interval for long-running operations
98
- retry_policy: Custom retry policy configuration
99
- logging_policy: Logging configuration
100
- user_agent_policy: Custom user agent settings
101
- proxy_policy: Proxy configuration
102
- authentication_policy: Authentication behavior settings
103
"""
104
```
105
106
### Multi-API Version Support
107
108
Leverage specific API versions for different operation groups or use the latest profile.
109
110
```python { .api }
111
# Using default profile with latest stable versions
112
client = AuthorizationManagementClient(credential, subscription_id)
113
114
# Using specific API version for all operations
115
client = AuthorizationManagementClient(
116
credential,
117
subscription_id,
118
api_version="2022-04-01"
119
)
120
121
# Using custom profile for mixed API versions
122
from azure.profiles import ProfileDefinition
123
124
custom_profile = ProfileDefinition({
125
"azure.mgmt.authorization.AuthorizationManagementClient": {
126
None: "2022-04-01",
127
'access_review_schedule_definitions': '2021-12-01-preview',
128
'role_assignment_schedules': '2020-10-01',
129
'alerts': '2022-08-01-preview'
130
}
131
})
132
133
client = AuthorizationManagementClient(
134
credential,
135
subscription_id,
136
profile=custom_profile
137
)
138
```
139
140
### Async Client Support
141
142
Use async operations for better performance in async applications.
143
144
```python { .api }
145
from azure.mgmt.authorization.aio import AuthorizationManagementClient
146
147
async def manage_roles_async():
148
"""Example of async client usage."""
149
async with AuthorizationManagementClient(
150
credential=credential,
151
subscription_id=subscription_id
152
) as client:
153
# Async operations
154
role_assignments = []
155
async for assignment in client.role_assignments.list_for_subscription():
156
role_assignments.append(assignment)
157
158
return role_assignments
159
```
160
161
## Usage Examples
162
163
### Basic Client Setup
164
165
```python
166
from azure.mgmt.authorization import AuthorizationManagementClient
167
from azure.identity import DefaultAzureCredential
168
169
# Simple setup with default credentials
170
credential = DefaultAzureCredential()
171
client = AuthorizationManagementClient(
172
credential=credential,
173
subscription_id="your-subscription-id"
174
)
175
176
# Use the client
177
role_assignments = list(client.role_assignments.list_for_subscription())
178
print(f"Found {len(role_assignments)} role assignments")
179
180
# Always close the client
181
client.close()
182
```
183
184
### Context Manager Usage
185
186
```python
187
# Recommended: Use context manager for automatic cleanup
188
with AuthorizationManagementClient(credential, subscription_id) as client:
189
# Client operations
190
role_definitions = list(client.role_definitions.list(
191
scope="/subscriptions/your-subscription-id"
192
))
193
194
for role_def in role_definitions:
195
print(f"Role: {role_def.role_name}")
196
print(f"Type: {role_def.role_type}")
197
198
# Client is automatically closed when exiting the context
199
```
200
201
### Service Principal Authentication
202
203
```python
204
from azure.identity import ClientSecretCredential
205
206
# Service principal authentication for automated scenarios
207
credential = ClientSecretCredential(
208
tenant_id="your-tenant-id",
209
client_id="your-app-id",
210
client_secret="your-app-secret"
211
)
212
213
client = AuthorizationManagementClient(
214
credential=credential,
215
subscription_id="your-subscription-id"
216
)
217
218
# Service principal can now perform authorized operations
219
permissions = client.permissions.list_for_resource_group("my-resource-group")
220
```
221
222
### Managed Identity Authentication
223
224
```python
225
from azure.identity import ManagedIdentityCredential
226
227
# For Azure resources (VMs, App Service, Functions, etc.)
228
credential = ManagedIdentityCredential()
229
230
client = AuthorizationManagementClient(
231
credential=credential,
232
subscription_id="your-subscription-id"
233
)
234
235
# Managed identity operations
236
deny_assignments = list(client.deny_assignments.list_for_subscription())
237
```
238
239
### Custom Configuration
240
241
```python
242
from azure.core.pipeline.policies import RetryPolicy
243
import logging
244
245
# Configure logging
246
logging.basicConfig(level=logging.DEBUG)
247
248
# Custom retry policy
249
retry_policy = RetryPolicy(
250
retry_total=5,
251
retry_backoff_factor=1.0,
252
retry_status_forcelist=[500, 502, 503, 504]
253
)
254
255
# Client with custom configuration
256
client = AuthorizationManagementClient(
257
credential=credential,
258
subscription_id=subscription_id,
259
logging_enable=True,
260
retry_policy=retry_policy,
261
polling_interval=30 # 30 seconds for long-running operations
262
)
263
```
264
265
### Multi-Subscription Management
266
267
```python
268
subscriptions = [
269
"subscription-1-id",
270
"subscription-2-id",
271
"subscription-3-id"
272
]
273
274
# Manage multiple subscriptions
275
for sub_id in subscriptions:
276
with AuthorizationManagementClient(credential, sub_id) as client:
277
print(f"\n=== Subscription: {sub_id} ===")
278
279
# List role assignments for each subscription
280
assignments = list(client.role_assignments.list_for_subscription())
281
print(f"Role assignments: {len(assignments)}")
282
283
# List alerts for each subscription
284
alerts = list(client.alerts.list_for_scope(f"/subscriptions/{sub_id}"))
285
print(f"Security alerts: {len(alerts)}")
286
```
287
288
### Environment-Specific Configuration
289
290
```python
291
import os
292
293
# Configuration based on environment
294
environment = os.getenv("ENVIRONMENT", "development")
295
296
if environment == "production":
297
# Production configuration
298
client = AuthorizationManagementClient(
299
credential=ManagedIdentityCredential(), # Use managed identity
300
subscription_id=os.getenv("PROD_SUBSCRIPTION_ID"),
301
base_url="https://management.azure.com",
302
logging_enable=False # Disable verbose logging
303
)
304
elif environment == "development":
305
# Development configuration
306
client = AuthorizationManagementClient(
307
credential=AzureCliCredential(), # Use CLI credentials
308
subscription_id=os.getenv("DEV_SUBSCRIPTION_ID"),
309
logging_enable=True, # Enable debugging
310
api_version="2022-04-01" # Pin to specific version
311
)
312
```
313
314
## Types
315
316
### Authentication Types
317
318
```python { .api }
319
from azure.core.credentials import TokenCredential
320
from azure.identity import (
321
DefaultAzureCredential,
322
ClientSecretCredential,
323
CertificateCredential,
324
ManagedIdentityCredential,
325
InteractiveBrowserCredential,
326
DeviceCodeCredential,
327
AzureCliCredential,
328
EnvironmentCredential,
329
SharedTokenCacheCredential
330
)
331
332
# TokenCredential interface - base for all credentials
333
class TokenCredential(Protocol):
334
def get_token(self, *scopes: str, **kwargs) -> AccessToken: ...
335
336
class AccessToken:
337
token: str
338
expires_on: int
339
```
340
341
### Configuration Types
342
343
```python { .api }
344
from azure.profiles import KnownProfiles, ProfileDefinition
345
from azure.core.pipeline.policies import (
346
RetryPolicy,
347
RedirectPolicy,
348
ProxyPolicy,
349
UserAgentPolicy,
350
HeadersPolicy
351
)
352
353
class KnownProfiles:
354
default: ProfileDefinition
355
latest: ProfileDefinition
356
357
class RetryPolicy:
358
def __init__(
359
self,
360
retry_total: int = 10,
361
retry_connect: int = 3,
362
retry_read: int = 3,
363
retry_status: int = 3,
364
retry_backoff_factor: float = 0.8,
365
retry_backoff_max: int = 120,
366
retry_status_forcelist: Optional[List[int]] = None,
367
retry_method_whitelist: Optional[List[str]] = None
368
): ...
369
```
370
371
### Pipeline Configuration Types
372
373
```python { .api }
374
from azure.core.pipeline import Pipeline
375
from azure.mgmt.core import ARMPipelineClient
376
377
class ARMPipelineClient:
378
def __init__(
379
self,
380
base_url: str,
381
config: Any,
382
**kwargs
383
): ...
384
385
# Common pipeline policies
386
class AuthenticationPolicy: ...
387
class BearerTokenCredentialPolicy: ...
388
class RequestIdPolicy: ...
389
class CustomHookPolicy: ...
390
class NetworkTraceLoggingPolicy: ...
391
class HttpLoggingPolicy: ...
392
```
393
394
## Constants
395
396
### Authentication Scopes
397
398
```python { .api }
399
class AuthenticationScopes:
400
MANAGEMENT = "https://management.azure.com/.default"
401
GRAPH = "https://graph.microsoft.com/.default"
402
VAULT = "https://vault.azure.net/.default"
403
STORAGE = "https://storage.azure.com/.default"
404
405
# Default scope for Authorization Management
406
DEFAULT_SCOPE = "https://management.azure.com/.default"
407
```
408
409
### Azure Endpoints
410
411
```python { .api }
412
class AzureEndpoints:
413
# Azure Public Cloud
414
PUBLIC_CLOUD = "https://management.azure.com"
415
416
# Azure Government Cloud
417
GOVERNMENT_CLOUD = "https://management.usgovcloudapi.net"
418
419
# Azure China Cloud
420
CHINA_CLOUD = "https://management.chinacloudapi.cn"
421
422
# Azure German Cloud (deprecated)
423
GERMAN_CLOUD = "https://management.microsoftazure.de"
424
```
425
426
### API Versions
427
428
```python { .api }
429
class SupportedApiVersions:
430
# Latest stable
431
LATEST_STABLE = "2022-04-01"
432
433
# Core RBAC versions
434
RBAC_2022_04_01 = "2022-04-01"
435
RBAC_2020_10_01 = "2020-10-01"
436
RBAC_2018_01_01_PREVIEW = "2018-01-01-preview"
437
438
# PIM versions
439
PIM_2020_10_01 = "2020-10-01"
440
PIM_2020_10_01_PREVIEW = "2020-10-01-preview"
441
442
# Access Reviews versions
443
ACCESS_REVIEWS_2021_12_01_PREVIEW = "2021-12-01-preview"
444
ACCESS_REVIEWS_2021_07_01_PREVIEW = "2021-07-01-preview"
445
446
# Alerts versions
447
ALERTS_2022_08_01_PREVIEW = "2022-08-01-preview"
448
```
449
450
## Error Handling
451
452
### Common Authentication Errors
453
454
```python { .api }
455
from azure.core.exceptions import (
456
ClientAuthenticationError,
457
HttpResponseError,
458
ServiceRequestError
459
)
460
from azure.identity import CredentialUnavailableError
461
462
# Authentication-specific exceptions
463
try:
464
client = AuthorizationManagementClient(credential, subscription_id)
465
roles = list(client.role_definitions.list(scope))
466
except ClientAuthenticationError as e:
467
print(f"Authentication failed: {e.message}")
468
# Handle: Check credentials, token expiry, permissions
469
except CredentialUnavailableError as e:
470
print(f"Credential unavailable: {e.message}")
471
# Handle: Credential source not available (CLI not logged in, etc.)
472
except HttpResponseError as e:
473
if e.status_code == 401:
474
print("Unauthorized - check credentials and permissions")
475
elif e.status_code == 403:
476
print("Forbidden - insufficient permissions")
477
```
478
479
### Configuration Validation
480
481
```python
482
def validate_client_config(credential, subscription_id):
483
"""Validate client configuration before use."""
484
try:
485
# Test credential by getting a token
486
token = credential.get_token("https://management.azure.com/.default")
487
if not token.token:
488
raise ValueError("Unable to obtain access token")
489
490
# Validate subscription ID format
491
if not subscription_id or len(subscription_id) != 36:
492
raise ValueError("Invalid subscription ID format")
493
494
# Test client connectivity
495
with AuthorizationManagementClient(credential, subscription_id) as client:
496
# Simple operation to verify connectivity
497
list(client.role_definitions.list(
498
scope=f"/subscriptions/{subscription_id}",
499
filter="$top=1"
500
))
501
502
return True
503
504
except Exception as e:
505
print(f"Client configuration validation failed: {e}")
506
return False
507
```
508
509
## Best Practices
510
511
### Security Best Practices
512
513
1. **Use Managed Identity**: Prefer managed identity over service principals when running on Azure
514
2. **Rotate Credentials**: Regularly rotate service principal secrets and certificates
515
3. **Least Privilege**: Grant minimum required permissions to service principals
516
4. **Secure Storage**: Never store credentials in code or configuration files
517
5. **Environment Variables**: Use secure environment variables or Azure Key Vault for secrets
518
519
### Performance Best Practices
520
521
1. **Connection Reuse**: Use context managers or explicitly close clients
522
2. **Async Operations**: Use async client for high-throughput scenarios
523
3. **Filtering**: Use OData filters to reduce data transfer
524
4. **Pagination**: Handle large result sets with proper pagination
525
5. **Caching**: Cache role definitions and other static data when appropriate
526
527
### Error Handling Best Practices
528
529
1. **Retry Logic**: Implement proper retry logic for transient failures
530
2. **Exponential Backoff**: Use exponential backoff for retry attempts
531
3. **Circuit Breaker**: Implement circuit breaker pattern for external dependencies
532
4. **Logging**: Log authentication events and errors for debugging
533
5. **Monitoring**: Monitor authentication failures and credential expiry