0
# Developer Tool Credentials
1
2
Authenticate using existing Azure developer tool sessions including Azure CLI, Azure PowerShell, Azure Developer CLI, and Visual Studio Code. These credentials enable seamless local development by leveraging existing authenticated sessions from developer tools.
3
4
## Capabilities
5
6
### AzureCliCredential
7
8
Authenticates by requesting tokens from the Azure CLI. Uses the account currently signed in via `az login` command, providing seamless authentication for local development without additional configuration.
9
10
```python { .api }
11
class AzureCliCredential:
12
def __init__(
13
self,
14
*,
15
process_timeout: int = 10,
16
**kwargs
17
):
18
"""
19
Create an AzureCliCredential that uses the Azure CLI for authentication.
20
21
Args:
22
process_timeout: Seconds to wait for the Azure CLI process to complete (default: 10)
23
24
Requirements:
25
- Azure CLI must be installed and available in PATH
26
- User must be signed in via 'az login'
27
- Azure CLI version 2.0.12 or later
28
"""
29
30
def get_token(self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs) -> AccessToken:
31
"""
32
Request an access token from Azure CLI.
33
34
Args:
35
*scopes: Desired scopes for the access token
36
claims: Additional claims required in the token (not supported by Azure CLI)
37
tenant_id: Optional tenant ID override (will switch Azure CLI context)
38
39
Returns:
40
AccessToken: The access token with expiration information
41
42
Raises:
43
CredentialUnavailableError: Azure CLI not installed, not logged in, or process failed
44
ClientAuthenticationError: Azure CLI returned invalid token response
45
"""
46
47
def get_token_info(self, *scopes: str, options: Optional[dict] = None) -> dict:
48
"""
49
Request access token with additional information from Azure CLI.
50
51
Args:
52
*scopes: Desired scopes for the access token
53
options: Additional options for token acquisition
54
55
Returns:
56
dict: Token information including access token and metadata
57
"""
58
```
59
60
**Usage Example:**
61
62
```python
63
from azure.identity import AzureCliCredential
64
from azure.identity import CredentialUnavailableError
65
66
try:
67
# Use current Azure CLI session
68
credential = AzureCliCredential()
69
70
# Test authentication
71
token = credential.get_token("https://management.azure.com/.default")
72
print("Azure CLI authentication successful")
73
74
except CredentialUnavailableError as e:
75
print("Azure CLI not available. Please run 'az login'")
76
print(f"Error: {e}")
77
78
# Use with Azure SDK clients
79
from azure.mgmt.resource import ResourceManagementClient
80
81
resource_client = ResourceManagementClient(
82
credential=AzureCliCredential(),
83
subscription_id="your-subscription-id"
84
)
85
86
# List resource groups using CLI authentication
87
for rg in resource_client.resource_groups.list():
88
print(f"Resource Group: {rg.name}")
89
90
# Custom timeout for slow CLI operations
91
slow_credential = AzureCliCredential(process_timeout=30)
92
```
93
94
**Azure CLI Setup:**
95
96
```bash
97
# Install Azure CLI
98
curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash
99
100
# Sign in to Azure
101
az login
102
103
# Sign in with specific tenant
104
az login --tenant your-tenant-id
105
106
# Set default subscription
107
az account set --subscription "your-subscription-id"
108
109
# Verify current account
110
az account show
111
```
112
113
### AzureDeveloperCliCredential
114
115
Authenticates by requesting tokens from the Azure Developer CLI (azd). Uses the account currently signed in via `azd auth login`, enabling authentication for Azure Developer CLI workflows and cloud-native application development.
116
117
```python { .api }
118
class AzureDeveloperCliCredential:
119
def __init__(
120
self,
121
*,
122
process_timeout: int = 10,
123
**kwargs
124
):
125
"""
126
Create an AzureDeveloperCliCredential that uses the Azure Developer CLI for authentication.
127
128
Args:
129
process_timeout: Seconds to wait for the Azure Developer CLI process to complete (default: 10)
130
131
Requirements:
132
- Azure Developer CLI (azd) must be installed and available in PATH
133
- User must be signed in via 'azd auth login'
134
- Azure Developer CLI version 0.4.0 or later
135
"""
136
137
def get_token(self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs) -> AccessToken:
138
"""
139
Request an access token from Azure Developer CLI.
140
141
Args:
142
*scopes: Desired scopes for the access token
143
claims: Additional claims required in the token (not supported by Azure Developer CLI)
144
tenant_id: Optional tenant ID override
145
146
Returns:
147
AccessToken: The access token with expiration information
148
149
Raises:
150
CredentialUnavailableError: Azure Developer CLI not installed, not logged in, or process failed
151
"""
152
153
def get_token_info(self, *scopes: str, options: Optional[dict] = None) -> dict:
154
"""
155
Request access token with additional information from Azure Developer CLI.
156
157
Args:
158
*scopes: Desired scopes for the access token
159
options: Additional options for token acquisition
160
161
Returns:
162
dict: Token information including access token and metadata
163
"""
164
```
165
166
**Usage Example:**
167
168
```python
169
from azure.identity import AzureDeveloperCliCredential
170
171
# Use Azure Developer CLI authentication
172
credential = AzureDeveloperCliCredential()
173
174
# Use with Azure SDK for cloud-native development
175
from azure.storage.blob import BlobServiceClient
176
177
blob_client = BlobServiceClient(
178
account_url="https://account.blob.core.windows.net",
179
credential=credential
180
)
181
182
# Deploy application resources using azd authentication
183
from azure.mgmt.containerinstance import ContainerInstanceManagementClient
184
185
container_client = ContainerInstanceManagementClient(
186
credential=credential,
187
subscription_id="your-subscription-id"
188
)
189
```
190
191
**Azure Developer CLI Setup:**
192
193
```bash
194
# Install Azure Developer CLI
195
curl -fsSL https://aka.ms/install-azd.sh | bash
196
197
# Sign in to Azure
198
azd auth login
199
200
# Initialize application
201
azd init
202
203
# Deploy application
204
azd up
205
```
206
207
### AzurePowerShellCredential
208
209
Authenticates by requesting tokens from Azure PowerShell. Uses the account currently signed in via `Connect-AzAccount` cmdlet, enabling authentication for PowerShell-based workflows and scripts.
210
211
```python { .api }
212
class AzurePowerShellCredential:
213
def __init__(
214
self,
215
*,
216
process_timeout: int = 10,
217
**kwargs
218
):
219
"""
220
Create an AzurePowerShellCredential that uses Azure PowerShell for authentication.
221
222
Args:
223
process_timeout: Seconds to wait for the Azure PowerShell process to complete (default: 10)
224
225
Requirements:
226
- Azure PowerShell module (Az) must be installed
227
- PowerShell must be available in PATH (powershell.exe on Windows, pwsh on others)
228
- User must be signed in via 'Connect-AzAccount'
229
"""
230
231
def get_token(self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs) -> AccessToken:
232
"""
233
Request an access token from Azure PowerShell.
234
235
Args:
236
*scopes: Desired scopes for the access token
237
claims: Additional claims required in the token (not supported by Azure PowerShell)
238
tenant_id: Optional tenant ID override
239
240
Returns:
241
AccessToken: The access token with expiration information
242
243
Raises:
244
CredentialUnavailableError: Azure PowerShell not installed, not logged in, or process failed
245
"""
246
247
def get_token_info(self, *scopes: str, options: Optional[dict] = None) -> dict:
248
"""
249
Request access token with additional information from Azure PowerShell.
250
251
Args:
252
*scopes: Desired scopes for the access token
253
options: Additional options for token acquisition
254
255
Returns:
256
dict: Token information including access token and metadata
257
"""
258
```
259
260
**Usage Example:**
261
262
```python
263
from azure.identity import AzurePowerShellCredential
264
265
# Use Azure PowerShell authentication
266
credential = AzurePowerShellCredential()
267
268
# Use with Azure management operations
269
from azure.mgmt.compute import ComputeManagementClient
270
271
compute_client = ComputeManagementClient(
272
credential=credential,
273
subscription_id="your-subscription-id"
274
)
275
276
# List virtual machines using PowerShell authentication
277
for vm in compute_client.virtual_machines.list_all():
278
print(f"VM: {vm.name}")
279
280
# Custom timeout for PowerShell operations
281
ps_credential = AzurePowerShellCredential(process_timeout=20)
282
```
283
284
**Azure PowerShell Setup:**
285
286
```powershell
287
# Install Azure PowerShell module
288
Install-Module -Name Az -AllowClobber -Force
289
290
# Sign in to Azure
291
Connect-AzAccount
292
293
# Sign in with specific tenant
294
Connect-AzAccount -Tenant "your-tenant-id"
295
296
# Set default subscription context
297
Set-AzContext -SubscriptionId "your-subscription-id"
298
299
# Verify current context
300
Get-AzContext
301
```
302
303
### VisualStudioCodeCredential
304
305
Authenticates using Azure account information stored by the Azure Account extension in Visual Studio Code. Enables seamless authentication for VS Code-based development workflows.
306
307
```python { .api }
308
class VisualStudioCodeCredential:
309
def __init__(
310
self,
311
*,
312
authority: Optional[str] = None,
313
tenant_id: Optional[str] = None,
314
**kwargs
315
):
316
"""
317
Create a VisualStudioCodeCredential that uses VS Code Azure Account extension.
318
319
Args:
320
authority: Authority of a Microsoft Entra endpoint
321
tenant_id: Microsoft Entra tenant ID to restrict authentication scope
322
323
Requirements:
324
- Visual Studio Code must be installed
325
- Azure Account extension must be installed and signed in
326
- Authentication data must be accessible in VS Code settings
327
"""
328
329
def get_token(self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs) -> AccessToken:
330
"""
331
Request an access token from Visual Studio Code Azure Account extension.
332
333
Args:
334
*scopes: Desired scopes for the access token
335
claims: Additional claims required in the token (not supported by VS Code)
336
tenant_id: Optional tenant ID override
337
338
Returns:
339
AccessToken: The access token with expiration information
340
341
Raises:
342
CredentialUnavailableError: VS Code not installed, Azure Account extension not available, or not signed in
343
"""
344
345
def get_token_info(self, *scopes: str, options: Optional[dict] = None) -> dict:
346
"""
347
Request access token with additional information from VS Code.
348
349
Args:
350
*scopes: Desired scopes for the access token
351
options: Additional options for token acquisition
352
353
Returns:
354
dict: Token information including access token and metadata
355
"""
356
```
357
358
**Usage Example:**
359
360
```python
361
from azure.identity import VisualStudioCodeCredential
362
363
# Use VS Code Azure Account extension authentication
364
credential = VisualStudioCodeCredential()
365
366
# Use in VS Code integrated development
367
from azure.keyvault.secrets import SecretClient
368
369
secret_client = SecretClient(
370
vault_url="https://vault.vault.azure.net/",
371
credential=credential
372
)
373
374
# Access secrets during development
375
try:
376
secret = secret_client.get_secret("api-key")
377
print("Retrieved secret successfully")
378
except Exception as e:
379
print(f"Failed to retrieve secret: {e}")
380
381
# Tenant-specific authentication in VS Code
382
tenant_credential = VisualStudioCodeCredential(
383
tenant_id="your-tenant-id"
384
)
385
```
386
387
**Visual Studio Code Setup:**
388
389
1. Install Visual Studio Code
390
2. Install Azure Account extension from VS Code marketplace
391
3. Open VS Code and sign in to Azure Account extension
392
4. Use `Ctrl+Shift+P` → "Azure: Sign In" to authenticate
393
394
### SharedTokenCacheCredential
395
396
Authenticates using tokens cached by Microsoft developer tools including Visual Studio, Azure CLI, and other Microsoft applications. Provides access to shared token cache for seamless cross-tool authentication.
397
398
```python { .api }
399
class SharedTokenCacheCredential:
400
def __init__(
401
self,
402
username: Optional[str] = None,
403
*,
404
authority: Optional[str] = None,
405
tenant_id: Optional[str] = None,
406
cache_persistence_options: Optional[TokenCachePersistenceOptions] = None,
407
**kwargs
408
):
409
"""
410
Create a SharedTokenCacheCredential that uses shared token cache from Microsoft tools.
411
412
Args:
413
username: Username (typically email address) to filter cached accounts
414
authority: Authority of a Microsoft Entra endpoint
415
tenant_id: Microsoft Entra tenant ID to restrict authentication scope
416
cache_persistence_options: Configuration for persistent token caching
417
418
Note:
419
This credential accesses tokens cached by Microsoft applications like Visual Studio,
420
Azure CLI, and other tools that use MSAL (Microsoft Authentication Library).
421
"""
422
423
@staticmethod
424
def supported() -> bool:
425
"""
426
Determine whether the shared token cache is supported on this platform.
427
428
Returns:
429
bool: True if shared token cache is supported, False otherwise
430
431
Note:
432
Shared token cache is primarily supported on Windows and macOS.
433
Linux support varies by distribution and installed tools.
434
"""
435
436
def get_token(self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs) -> AccessToken:
437
"""
438
Request an access token from the shared token cache.
439
440
Args:
441
*scopes: Desired scopes for the access token
442
claims: Additional claims required in the token
443
tenant_id: Optional tenant ID override
444
445
Returns:
446
AccessToken: The access token with expiration information
447
448
Raises:
449
CredentialUnavailableError: No valid tokens in shared cache or cache not supported
450
"""
451
452
def get_token_info(self, *scopes: str, options: Optional[dict] = None) -> dict:
453
"""
454
Request access token with additional information from shared cache.
455
456
Args:
457
*scopes: Desired scopes for the access token
458
options: Additional options for token acquisition
459
460
Returns:
461
dict: Token information including access token and metadata
462
"""
463
```
464
465
**Usage Example:**
466
467
```python
468
from azure.identity import SharedTokenCacheCredential
469
470
# Check if shared token cache is supported
471
if SharedTokenCacheCredential.supported():
472
# Use shared token cache for seamless authentication
473
credential = SharedTokenCacheCredential()
474
475
# Filter by specific username if multiple accounts cached
476
user_credential = SharedTokenCacheCredential(
477
username="user@example.com"
478
)
479
480
# Use with Azure SDK
481
from azure.storage.blob import BlobServiceClient
482
483
blob_client = BlobServiceClient(
484
account_url="https://account.blob.core.windows.net",
485
credential=credential
486
)
487
else:
488
print("Shared token cache not supported on this platform")
489
# Fall back to other authentication method
490
```
491
492
## Developer Credential Integration Patterns
493
494
### DefaultAzureCredential with Developer Tools
495
496
```python
497
from azure.identity import DefaultAzureCredential
498
499
# DefaultAzureCredential automatically includes developer credentials
500
# in this order (after environment and managed identity):
501
# 1. SharedTokenCacheCredential
502
# 2. VisualStudioCodeCredential (excluded by default)
503
# 3. AzureCliCredential
504
# 4. AzurePowerShellCredential
505
# 5. AzureDeveloperCliCredential
506
507
credential = DefaultAzureCredential()
508
509
# Customize which developer credentials are included
510
dev_credential = DefaultAzureCredential(
511
exclude_cli_credential=False, # Include Azure CLI
512
exclude_powershell_credential=False, # Include Azure PowerShell
513
exclude_developer_cli_credential=False, # Include Azure Developer CLI
514
exclude_visual_studio_code_credential=False, # Include VS Code
515
exclude_shared_token_cache_credential=False # Include shared cache
516
)
517
518
# Development-only configuration
519
local_dev_credential = DefaultAzureCredential(
520
exclude_managed_identity_credential=True, # Skip managed identity locally
521
exclude_environment_credential=True, # Skip environment variables
522
exclude_workload_identity_credential=True # Skip workload identity
523
)
524
```
525
526
### Custom Developer Credential Chain
527
528
```python
529
from azure.identity import ChainedTokenCredential, AzureCliCredential, AzurePowerShellCredential
530
531
# Create custom developer credential chain
532
dev_chain = ChainedTokenCredential(
533
AzureCliCredential(), # Try Azure CLI first
534
AzurePowerShellCredential(), # Fall back to PowerShell
535
VisualStudioCodeCredential() # Fall back to VS Code
536
)
537
538
# Use in development environment
539
from azure.keyvault.secrets import SecretClient
540
541
secret_client = SecretClient(
542
vault_url="https://vault.vault.azure.net/",
543
credential=dev_chain
544
)
545
```
546
547
### Environment Detection and Fallback
548
549
```python
550
import os
551
from azure.identity import (
552
DefaultAzureCredential,
553
AzureCliCredential,
554
CredentialUnavailableError
555
)
556
557
def get_development_credential():
558
"""Get appropriate credential for current development environment."""
559
560
# Check if running in Azure (production)
561
if os.environ.get("WEBSITE_SITE_NAME") or os.environ.get("FUNCTIONS_WORKER_RUNTIME"):
562
# Use DefaultAzureCredential for managed identity in Azure
563
return DefaultAzureCredential()
564
565
# Local development - try developer tools
566
try:
567
# Test Azure CLI first (most common)
568
cli_credential = AzureCliCredential()
569
cli_credential.get_token("https://management.azure.com/.default")
570
return cli_credential
571
except CredentialUnavailableError:
572
pass
573
574
# Fall back to full DefaultAzureCredential chain
575
return DefaultAzureCredential(
576
exclude_managed_identity_credential=True # Skip in local dev
577
)
578
579
# Use in application
580
credential = get_development_credential()
581
```
582
583
## Troubleshooting Developer Credentials
584
585
### Common Issues and Solutions
586
587
```python
588
from azure.identity import AzureCliCredential, CredentialUnavailableError
589
import subprocess
590
import logging
591
592
# Enable debug logging
593
logging.basicConfig(level=logging.DEBUG)
594
595
def diagnose_azure_cli():
596
"""Diagnose Azure CLI authentication issues."""
597
try:
598
# Check if Azure CLI is installed
599
result = subprocess.run(["az", "--version"], capture_output=True, text=True)
600
print(f"Azure CLI version: {result.stdout}")
601
602
# Check current account
603
result = subprocess.run(["az", "account", "show"], capture_output=True, text=True)
604
if result.returncode == 0:
605
print("Azure CLI is logged in")
606
print(result.stdout)
607
else:
608
print("Azure CLI not logged in. Run 'az login'")
609
610
except FileNotFoundError:
611
print("Azure CLI not installed")
612
except Exception as e:
613
print(f"Error checking Azure CLI: {e}")
614
615
def test_credential_chain():
616
"""Test different developer credentials."""
617
from azure.identity import (
618
AzureCliCredential,
619
AzurePowerShellCredential,
620
VisualStudioCodeCredential,
621
SharedTokenCacheCredential
622
)
623
624
credentials = [
625
("Azure CLI", AzureCliCredential()),
626
("Azure PowerShell", AzurePowerShellCredential()),
627
("VS Code", VisualStudioCodeCredential()),
628
("Shared Cache", SharedTokenCacheCredential())
629
]
630
631
for name, credential in credentials:
632
try:
633
token = credential.get_token("https://management.azure.com/.default")
634
print(f"✓ {name}: Successfully acquired token")
635
except CredentialUnavailableError as e:
636
print(f"✗ {name}: {e}")
637
except Exception as e:
638
print(f"✗ {name}: Unexpected error - {e}")
639
640
# Run diagnostics
641
diagnose_azure_cli()
642
test_credential_chain()
643
```
644
645
### Process Timeout Configuration
646
647
```python
648
from azure.identity import AzureCliCredential, AzurePowerShellCredential
649
650
# Increase timeout for slow systems or networks
651
slow_cli = AzureCliCredential(process_timeout=30)
652
slow_ps = AzurePowerShellCredential(process_timeout=30)
653
654
# Decrease timeout for responsive systems
655
fast_cli = AzureCliCredential(process_timeout=5)
656
```
657
658
### Cross-Platform Considerations
659
660
```python
661
import platform
662
from azure.identity import DefaultAzureCredential
663
664
def get_platform_appropriate_credential():
665
"""Get credential appropriate for current platform."""
666
system = platform.system()
667
668
if system == "Windows":
669
# Windows supports all developer credentials
670
return DefaultAzureCredential(
671
exclude_visual_studio_code_credential=False
672
)
673
elif system == "Darwin": # macOS
674
# macOS supports most developer credentials
675
return DefaultAzureCredential(
676
exclude_powershell_credential=False # PowerShell Core available on macOS
677
)
678
else: # Linux and others
679
# Linux primarily supports Azure CLI and PowerShell Core
680
return DefaultAzureCredential(
681
exclude_visual_studio_code_credential=True, # Limited support
682
exclude_shared_token_cache_credential=True # Limited support
683
)
684
685
credential = get_platform_appropriate_credential()
686
```