azure-identity-py
microsoft/skills
使用 Microsoft Entra ID 搭配 DefaultAzureCredential、託管身分識別、服務主體及憑證快取,從 Python 對 Azure 服務進行驗證。
...展開全部適用於 Python 的 Azure Identity 函式庫
適用於使用 Microsoft Entra ID 的 Azure SDK 客戶端的驗證函式庫。
在以下情況下使用此功能:
- 應用程式需要透過 Python 向 Azure 服務進行身份驗證時
- 您需要
DefaultAzureCredential進行本地端開發與 Azure 部署 - 您需要
ManagedIdentityCredential適用於由 Azure 託管的工作負載 - 您需要使用密鑰或憑證進行服務主體驗證
- 您需要透過以下方式直接取得憑證
get_token() - 您需要排除憑證鏈失敗的問題
安裝
pip install azure-identity
針對 VS Code 或基於中介服務器的桌面驗證:
pip install azure-identity-broker
Python 版本
azure-identity 支援 Python 3.9 以上版本。
環境變數
# Service principal with client secret
AZURE_TENANT_ID=
AZURE_CLIENT_ID=
AZURE_CLIENT_SECRET=
# Service principal with certificate
AZURE_TENANT_ID=
AZURE_CLIENT_ID=
AZURE_CLIENT_CERTIFICATE_PATH=/path/to/cert.pem
AZURE_CLIENT_CERTIFICATE_PASSWORD=
# Authority (sovereign clouds)
AZURE_AUTHORITY_HOST=login.microsoftonline.com # Default; or login.chinacloudapi.cn, login.microsoftonline.us
# User-assigned managed identity
AZURE_CLIENT_ID=
# Credential selection (new)
AZURE_TOKEN_CREDENTIALS=dev|prod| # Optional, restricts DAC chain
DefaultAzureCredential
適用於大多數情境的建議憑證。會依序嘗試多種驗證方法:
from azure.identity import DefaultAzureCredential
from azure.storage.blob import BlobServiceClient
# Works in local dev AND production without code changes
credential = DefaultAzureCredential()
with BlobServiceClient(
account_url="https://.blob.core.windows.net",
credential=credential
) as client:
containers = list(client.list_containers())
憑證鏈順序
請參閱 DefaultAzureCredential 概述,了解當前的憑證鏈順序與預設值。
自訂 DefaultAzureCredential
# Exclude credentials you don't need
credential = DefaultAzureCredential(
exclude_environment_credential=True,
exclude_shared_token_cache_credential=True,
managed_identity_client_id="" # For user-assigned MI (also accepts object ID or resource ID)
)
# Enable interactive browser (disabled by default)
credential = DefaultAzureCredential(
exclude_interactive_browser_credential=False
)
# Set subprocess timeout for CLI-based credentials (default: 10s)
credential = DefaultAzureCredential(process_timeout=30)
# Require AZURE_TOKEN_CREDENTIALS env var to be set
credential = DefaultAzureCredential(require_envvar=True)
排除參數
| 參數 | 預設值 | 效果 |
|---|---|---|
exclude_environment_credential |
False | 跳過基於環境變數的驗證 |
exclude_workload_identity_credential |
False | 跳過 Kubernetes 工作負載身分識別 |
exclude_managed_identity_credential |
false | 跳過託管身分識別 |
exclude_shared_token_cache_credential |
false | 跳過共用代幣快取 |
exclude_visual_studio_code_credential |
否 | 跳過 VS Code 憑證 |
exclude_cli_credential |
否 | 跳過 Azure CLI |
exclude_powershell_credential |
false | 跳過 Azure PowerShell |
exclude_developer_cli_credential |
false | 跳過 Azure Developer CLI |
exclude_interactive_browser_credential |
是 | 跳過互動式瀏覽器 |
exclude_broker_credential |
False | 跳過 WAM 中介伺服器 |
get_bearer_token_provider
將憑證封裝成可呼叫函式,並回傳 Bearer 憑證字串的輔助函式。對於 OpenAI SDK 及其他非 Azure SDK 客戶端而言至關重要:
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
credential = DefaultAzureCredential()
token_provider = get_bearer_token_provider(
credential, "https://cognitiveservices.azure.com/.default"
)
# Use with OpenAI SDK
from openai import AzureOpenAI
with AzureOpenAI(
azure_endpoint="https://.openai.azure.com/",
azure_ad_token_provider=token_provider,
api_version="2024-10-21",
) as client:
# response = client.chat.completions.create(...)
...
憑證類型
憑證鏈
| 憑證 | 使用案例 |
|---|---|
DefaultAzureCredential |
大多數情境 — 自動偵測環境 |
ChainedTokenCredential |
具有明確排序的自訂憑證鏈 |
Azure 託管應用程式
| 憑證 | 使用案例 |
|---|---|
EnvironmentCredential |
透過 AZURE_CLIENT_SECRET / AZURE_CLIENT_CERTIFICATE_PATH 環境變數進行驗證 |
ManagedIdentityCredential |
Azure 虛擬機器、App Service、Functions、AKS、Arc、Service Fabric |
WorkloadIdentityCredential |
搭配 Microsoft Entra Workload ID 的 Kubernetes |
服務主體
| 憑證 | 使用案例 |
|---|---|
ClientSecretCredential |
具備客戶端祕鑰的服務主體 |
CertificateCredential |
具備 PEM/PKCS12 憑證的服務主體 |
ClientAssertionCredential |
具備已簽署 JWT 斷言的服務主體 |
AzurePipelinesCredential |
具備工作負載身分聯邦功能的 Azure Pipelines |
OnBehalfOfCredential |
中層「代表」流程(委派使用者身分) |
使用者驗證
| 憑證 | 用例 |
|---|---|
InteractiveBrowserCredential |
互動式瀏覽器 OAuth 登入 |
DeviceCodeCredential |
無頭/SSH 裝置代碼流程 |
AuthorizationCodeCredential |
先前取得的授權碼 |
開發者工具
| 憑證 | 使用案例 |
|---|---|
AzureCliCredential |
az login |
AzureDeveloperCliCredential |
azd auth login |
AzurePowerShellCredential |
Connect-AzAccount |
VisualStudioCodeCredential |
VS Code Azure Resources 擴充功能 |
具體憑證範例
ManagedIdentityCredential
適用於由 Azure 託管的資源(虛擬機器、App Service、Functions、AKS):
from azure.identity import ManagedIdentityCredential
# System-assigned managed identity
credential = ManagedIdentityCredential()
# User-assigned managed identity (client_id, object_id, or resource_id)
credential = ManagedIdentityCredential(
client_id=""
)
# Also valid:
# credential = ManagedIdentityCredential(object_id="")
# credential = ManagedIdentityCredential(resource_id="")
ClientSecretCredential
import os
from azure.identity import ClientSecretCredential
credential = ClientSecretCredential(
tenant_id=os.environ["AZURE_TENANT_ID"],
client_id=os.environ["AZURE_CLIENT_ID"],
client_secret=os.environ["AZURE_CLIENT_SECRET"],
)
CertificateCredential
注意:此類別
CertificateCredential,而非ClientCertificateCredential.
from azure.identity import CertificateCredential
# From file path
credential = CertificateCredential(
tenant_id="",
client_id="",
certificate_path="/path/to/cert.pem",
)
# From bytes with password
credential = CertificateCredential(
tenant_id="",
client_id="",
certificate_data=cert_bytes,
password="",
send_certificate_chain=True, # Required for SNI auth
)
AzureCliCredential
from azure.identity import AzureCliCredential
credential = AzureCliCredential()
# With tenant restriction
credential = AzureCliCredential(tenant_id="")
ChainedTokenCredential
自訂憑證鏈:
from azure.identity import (
ChainedTokenCredential,
ManagedIdentityCredential,
AzureCliCredential,
)
# Try managed identity first, fall back to CLI
credential = ChainedTokenCredential(
ManagedIdentityCredential(client_id=""),
AzureCliCredential(),
)
WorkloadIdentityCredential
適用於具備工作負載身分識別的 Azure Kubernetes Service:
from azure.identity import WorkloadIdentityCredential
# Reads from AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_FEDERATED_TOKEN_FILE
credential = WorkloadIdentityCredential()
# Or explicit configuration
credential = WorkloadIdentityCredential(
tenant_id="",
client_id="",
token_file_path="/var/run/secrets/azure/tokens/azure-identity-token",
)
裝置代碼憑證
適用於無頭裝置(IoT、SSH、CLI 工具):
from azure.identity import DeviceCodeCredential
credential = DeviceCodeCredential()
# Prints device code prompt to stdout by default
# With custom prompt callback
def prompt_callback(verification_uri, user_code, expires_on):
print(f"Go to {verification_uri} and enter code {user_code}")
credential = DeviceCodeCredential(
client_id="",
prompt_callback=prompt_callback,
)
互動式瀏覽器憑證
適用於互動式 OAuth 瀏覽器登入:
from azure.identity import InteractiveBrowserCredential
credential = InteractiveBrowserCredential()
# With specific tenant and client
credential = InteractiveBrowserCredential(
tenant_id="",
client_id="",
)
OnBehalfOfCredential
適用於傳遞使用者身分的中階服務:
from azure.identity import OnBehalfOfCredential
credential = OnBehalfOfCredential(
tenant_id="",
client_id="",
client_secret="",
user_assertion="",
)
AzurePipelinesCredential
適用於具有工作負載身分聯邦功能的 Azure DevOps 管線:
import os
from azure.identity import AzurePipelinesCredential
credential = AzurePipelinesCredential(
tenant_id="",
client_id="",
service_connection_id="",
system_access_token=os.environ["SYSTEM_ACCESSTOKEN"],
)
直接取得憑證
from azure.identity import DefaultAzureCredential
with DefaultAzureCredential() as credential:
# Get token for a specific scope
token = credential.get_token("https://management.azure.com/.default")
print(f"Token expires: {token.expires_on}")
# For Azure Database for PostgreSQL
token = credential.get_token("https://ossrdbms-aad.database.windows.net/.default")
非同步憑證
非同步憑證位於 azure.identity.aio中。請務必關閉它們,或使用 async with:
from azure.identity.aio import DefaultAzureCredential
from azure.storage.blob.aio import BlobServiceClient
async def main():
# Preferred: use async context manager for both credential and client
async with DefaultAzureCredential() as credential:
async with BlobServiceClient(
account_url="https://.blob.core.windows.net",
credential=credential,
) as client:
# ... async operations
pass
「非同步」
get_bearer_token_provider位於azure.identity.aio.get_bearer_token_provider.
主權雲端
請使用 AzureAuthorityHosts 或 AZURE_AUTHORITY_HOST 環境變數:
from azure.identity import DefaultAzureCredential, AzureAuthorityHosts
# Azure Government
credential = DefaultAzureCredential(authority=AzureAuthorityHosts.AZURE_GOVERNMENT)
# Azure China
credential = DefaultAzureCredential(authority=AzureAuthorityHosts.AZURE_CHINA)
| 常數 | 權限 |
|---|---|
AzureAuthorityHosts.AZURE_PUBLIC_CLOUD |
login.microsoftonline.com (預設) |
AzureAuthorityHosts.AZURE_GOVERNMENT |
login.microsoftonline.us |
AzureAuthorityHosts.AZURE_CHINA |
login.chinacloudapi.cn |
持久化憑證快取
可選擇啟用的磁碟型快取,支援 TokenCachePersistenceOptions:
from azure.identity import DefaultAzureCredential, TokenCachePersistenceOptions
credential = DefaultAzureCredential(
cache_persistence_options=TokenCachePersistenceOptions()
)
# Allow unencrypted fallback (NOT recommended for production)
credential = DefaultAzureCredential(
cache_persistence_options=TokenCachePersistenceOptions(allow_unencrypted_storage=True)
)
儲存:Windows (DPAPI)、macOS (Keychain)、Linux (Keyring)。
多租戶支援
允許為除已配置租戶以外的其他租戶取得憑證:
from azure.identity import ClientSecretCredential
credential = ClientSecretCredential(
tenant_id="",
client_id="",
client_secret="",
additionally_allowed_tenants=["", "*"], # "*" allows any tenant
)
錯誤處理
from azure.identity import DefaultAzureCredential, CredentialUnavailableError
from azure.core.exceptions import ClientAuthenticationError
with DefaultAzureCredential() as credential:
try:
token = credential.get_token("https://management.azure.com/.default")
except CredentialUnavailableError:
# No credential in the chain could attempt authentication
pass
except ClientAuthenticationError as e:
# Authentication was attempted but failed
# e.message contains details from each credential in the chain
pass
記錄
啟用認證記錄以供除錯使用:
import logging
# Enable verbose Azure Identity logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("azure.identity")
logger.setLevel(logging.DEBUG)
# Or via environment variable
AZURE_LOG_LEVEL=debug
憑證選擇對照表
| 環境 | 建議的憑證 |
|---|---|
| 本地開發 | DefaultAzureCredential (使用 Azure CLI) |
| Azure 應用程式服務 | DefaultAzureCredential (使用託管身分識別) |
| Azure Functions | DefaultAzureCredential (使用託管身分識別) |
| Azure Kubernetes Service | WorkloadIdentityCredential |
| Azure 虛擬機器 | DefaultAzureCredential (使用託管身分識別) |
| CI/CD 管線 | EnvironmentCredential 或 AzurePipelinesCredential |
| 桌面應用程式 | InteractiveBrowserCredential |
| 命令列介面 (CLI) / 無介面工具 | DeviceCodeCredential |
| 中階服務 | OnBehalfOfCredential |
最佳實務
- 請選擇同步或非同步,並保持一致。請勿混合使用
azure.xxx同步客戶端與azure.xxx.aio非同步客戶端混合使用。每個模組應選擇一種模式。 - 若模組擁有您希望清理的憑證快取/HTTP 傳輸通道,請將憑證用作上下文管理器(
with DefaultAzureCredential() as credential:),當其擁有您希望進行清理的標記快取/HTTP 傳輸時;對於非同步模式,請使用async with來自azure.identity.aio. - 對於在本地執行的程式碼,請使用
DefaultAzureCredential。對於在 Azure 中執行的程式碼,請使用特定的令牌憑證。 - 切勿將憑證硬編碼 — 請使用環境變數或託管身分識別
- 在 Azure 生產環境部署中,建議優先使用受管身分識別
- 對於非 Azure SDK 客戶端(OpenAI、REST API),請使用
get_bearer_token_provider - 當您需要自訂憑證順序時,請使用 `
ChainedTokenCredential` - 針對使用者指派的託管身分識別,請設定
AZURE_CLIENT_ID(物件 ID 和資源 ID 也是有效的識別碼) - 排除未使用的憑證以加快
DefaultAzureCredential驗證 - 請使用 `
CertificateCredential`(而非ClientCertificateCredential— 該名稱不存在) - 為長期運行的服務啟用
cache_persistence_options以減少令牌請求 - 重複使用憑證實例 — 同一組憑證可在多個客戶端間共用
參考連結
| 資源 | URL |
|---|---|
| PyPI 套件 | https://pypi.org/project/azure-identity/ |
| API 參考手冊 | https://learn.microsoft.com/python/api/azure-identity |
| GitHub 原始碼 | https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity |
| 憑證鏈 | https://aka.ms/azsdk/python/identity/credential-chains |
---
name: azure-identity-py
description: Authenticate to Azure services from Python using Microsoft Entra ID with DefaultAzureCredential, managed identity, service principals, and token caching.
license: MIT
---
# Azure Identity library for Python
Authentication library for Azure SDK clients using Microsoft Entra ID.
Use this skill when:
- An app needs to authenticate to Azure services from Python
- You need `DefaultAzureCredential` for local dev + Azure deployment
- You need `ManagedIdentityCredential` for Azure-hosted workloads
- You need service principal auth with secret or certificate
- You need direct token acquisition with `get_token()`
- You need to troubleshoot credential chain failures
## Installation
```bash
pip install azure-identity
```
For VS Code or broker-based desktop auth:
```bash
pip install azure-identity-broker
```
## Python Version
`azure-identity` supports Python 3.9+.
## Environment Variables
```bash
# Service principal with client secret
AZURE_TENANT_ID=<your-tenant-id>
AZURE_CLIENT_ID=<your-client-id>
AZURE_CLIENT_SECRET=<your-client-secret>
# Service principal with certificate
AZURE_TENANT_ID=<your-tenant-id>
AZURE_CLIENT_ID=<your-client-id>
AZURE_CLIENT_CERTIFICATE_PATH=/path/to/cert.pem
AZURE_CLIENT_CERTIFICATE_PASSWORD=<optional-password>
# Authority (sovereign clouds)
AZURE_AUTHORITY_HOST=login.microsoftonline.com # Default; or login.chinacloudapi.cn, login.microsoftonline.us
# User-assigned managed identity
AZURE_CLIENT_ID=<managed-identity-client-id>
# Credential selection (new)
AZURE_TOKEN_CREDENTIALS=dev|prod|<credential-name> # Optional, restricts DAC chain
```
## DefaultAzureCredential
The recommended credential for most scenarios. Tries multiple authentication methods in order:
```python
from azure.identity import DefaultAzureCredential
from azure.storage.blob import BlobServiceClient
# Works in local dev AND production without code changes
credential = DefaultAzureCredential()
with BlobServiceClient(
account_url="https://<account>.blob.core.windows.net",
credential=credential
) as client:
containers = list(client.list_containers())
```
### Credential Chain Order
See [DefaultAzureCredential overview](https://aka.ms/azsdk/python/identity/credential-chains#defaultazurecredential-overview) for the current credential chain order and defaults.
### Customizing DefaultAzureCredential
```python
# Exclude credentials you don't need
credential = DefaultAzureCredential(
exclude_environment_credential=True,
exclude_shared_token_cache_credential=True,
managed_identity_client_id="<user-assigned-mi-client-id>" # For user-assigned MI (also accepts object ID or resource ID)
)
# Enable interactive browser (disabled by default)
credential = DefaultAzureCredential(
exclude_interactive_browser_credential=False
)
# Set subprocess timeout for CLI-based credentials (default: 10s)
credential = DefaultAzureCredential(process_timeout=30)
# Require AZURE_TOKEN_CREDENTIALS env var to be set
credential = DefaultAzureCredential(require_envvar=True)
```
### Exclude Parameters
| Parameter | Default | Effect |
|-----------|---------|--------|
| `exclude_environment_credential` | False | Skip env-var-based auth |
| `exclude_workload_identity_credential` | False | Skip Kubernetes workload identity |
| `exclude_managed_identity_credential` | False | Skip managed identity |
| `exclude_shared_token_cache_credential` | False | Skip shared token cache |
| `exclude_visual_studio_code_credential` | False | Skip VS Code credential |
| `exclude_cli_credential` | False | Skip Azure CLI |
| `exclude_powershell_credential` | False | Skip Azure PowerShell |
| `exclude_developer_cli_credential` | False | Skip Azure Developer CLI |
| `exclude_interactive_browser_credential` | **True** | Skip interactive browser |
| `exclude_broker_credential` | False | Skip WAM broker |
## get_bearer_token_provider
Helper that wraps a credential into a callable returning a bearer token string. Essential for OpenAI SDK and other non-Azure-SDK clients:
```python
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
credential = DefaultAzureCredential()
token_provider = get_bearer_token_provider(
credential, "https://cognitiveservices.azure.com/.default"
)
# Use with OpenAI SDK
from openai import AzureOpenAI
with AzureOpenAI(
azure_endpoint="https://<resource>.openai.azure.com/",
azure_ad_token_provider=token_provider,
api_version="2024-10-21",
) as client:
# response = client.chat.completions.create(...)
...
```
## Credential Types
### Credential Chains
| Credential | Use Case |
|------------|----------|
| `DefaultAzureCredential` | Most scenarios — auto-detects environment |
| `ChainedTokenCredential` | Custom credential chain with explicit ordering |
### Azure-Hosted Applications
| Credential | Use Case |
|------------|----------|
| `EnvironmentCredential` | Auth via AZURE_CLIENT_SECRET / AZURE_CLIENT_CERTIFICATE_PATH env vars |
| `ManagedIdentityCredential` | Azure VMs, App Service, Functions, AKS, Arc, Service Fabric |
| `WorkloadIdentityCredential` | Kubernetes with Microsoft Entra Workload ID |
### Service Principals
| Credential | Use Case |
|------------|----------|
| `ClientSecretCredential` | Service principal with client secret |
| `CertificateCredential` | Service principal with PEM/PKCS12 certificate |
| `ClientAssertionCredential` | Service principal with signed JWT assertion |
| `AzurePipelinesCredential` | Azure Pipelines with workload identity federation |
| `OnBehalfOfCredential` | Middle-tier on-behalf-of flow (delegated user identity) |
### User Authentication
| Credential | Use Case |
|------------|----------|
| `InteractiveBrowserCredential` | Interactive browser OAuth sign-in |
| `DeviceCodeCredential` | Headless/SSH device code flow |
| `AuthorizationCodeCredential` | Previously obtained authorization code |
### Developer Tools
| Credential | Use Case |
|------------|----------|
| `AzureCliCredential` | `az login` |
| `AzureDeveloperCliCredential` | `azd auth login` |
| `AzurePowerShellCredential` | `Connect-AzAccount` |
| `VisualStudioCodeCredential` | VS Code Azure Resources extension |
## Specific Credential Examples
### ManagedIdentityCredential
For Azure-hosted resources (VMs, App Service, Functions, AKS):
```python
from azure.identity import ManagedIdentityCredential
# System-assigned managed identity
credential = ManagedIdentityCredential()
# User-assigned managed identity (client_id, object_id, or resource_id)
credential = ManagedIdentityCredential(
client_id="<user-assigned-mi-client-id>"
)
# Also valid:
# credential = ManagedIdentityCredential(object_id="<object-id>")
# credential = ManagedIdentityCredential(resource_id="<resource-id>")
```
### ClientSecretCredential
```python
import os
from azure.identity import ClientSecretCredential
credential = ClientSecretCredential(
tenant_id=os.environ["AZURE_TENANT_ID"],
client_id=os.environ["AZURE_CLIENT_ID"],
client_secret=os.environ["AZURE_CLIENT_SECRET"],
)
```
### CertificateCredential
> **Note:** The class is `CertificateCredential`, NOT `ClientCertificateCredential`.
```python
from azure.identity import CertificateCredential
# From file path
credential = CertificateCredential(
tenant_id="<tenant-id>",
client_id="<client-id>",
certificate_path="/path/to/cert.pem",
)
# From bytes with password
credential = CertificateCredential(
tenant_id="<tenant-id>",
client_id="<client-id>",
certificate_data=cert_bytes,
password="<cert-password>",
send_certificate_chain=True, # Required for SNI auth
)
```
### AzureCliCredential
```python
from azure.identity import AzureCliCredential
credential = AzureCliCredential()
# With tenant restriction
credential = AzureCliCredential(tenant_id="<tenant-id>")
```
### ChainedTokenCredential
Custom credential chain:
```python
from azure.identity import (
ChainedTokenCredential,
ManagedIdentityCredential,
AzureCliCredential,
)
# Try managed identity first, fall back to CLI
credential = ChainedTokenCredential(
ManagedIdentityCredential(client_id="<user-assigned-mi-client-id>"),
AzureCliCredential(),
)
```
### WorkloadIdentityCredential
For Azure Kubernetes Service with workload identity:
```python
from azure.identity import WorkloadIdentityCredential
# Reads from AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_FEDERATED_TOKEN_FILE
credential = WorkloadIdentityCredential()
# Or explicit configuration
credential = WorkloadIdentityCredential(
tenant_id="<tenant-id>",
client_id="<client-id>",
token_file_path="/var/run/secrets/azure/tokens/azure-identity-token",
)
```
### DeviceCodeCredential
For headless devices (IoT, SSH, CLI tools):
```python
from azure.identity import DeviceCodeCredential
credential = DeviceCodeCredential()
# Prints device code prompt to stdout by default
# With custom prompt callback
def prompt_callback(verification_uri, user_code, expires_on):
print(f"Go to {verification_uri} and enter code {user_code}")
credential = DeviceCodeCredential(
client_id="<client-id>",
prompt_callback=prompt_callback,
)
```
### InteractiveBrowserCredential
For interactive OAuth browser sign-in:
```python
from azure.identity import InteractiveBrowserCredential
credential = InteractiveBrowserCredential()
# With specific tenant and client
credential = InteractiveBrowserCredential(
tenant_id="<tenant-id>",
client_id="<client-id>",
)
```
### OnBehalfOfCredential
For middle-tier services propagating user identity:
```python
from azure.identity import OnBehalfOfCredential
credential = OnBehalfOfCredential(
tenant_id="<tenant-id>",
client_id="<client-id>",
client_secret="<client-secret>",
user_assertion="<access-token-from-client>",
)
```
### AzurePipelinesCredential
For Azure DevOps pipelines with workload identity federation:
```python
import os
from azure.identity import AzurePipelinesCredential
credential = AzurePipelinesCredential(
tenant_id="<tenant-id>",
client_id="<client-id>",
service_connection_id="<service-connection-id>",
system_access_token=os.environ["SYSTEM_ACCESSTOKEN"],
)
```
## Getting Tokens Directly
```python
from azure.identity import DefaultAzureCredential
with DefaultAzureCredential() as credential:
# Get token for a specific scope
token = credential.get_token("https://management.azure.com/.default")
print(f"Token expires: {token.expires_on}")
# For Azure Database for PostgreSQL
token = credential.get_token("https://ossrdbms-aad.database.windows.net/.default")
```
## Async Credentials
Async credentials are in `azure.identity.aio`. Always close them or use `async with`:
```python
from azure.identity.aio import DefaultAzureCredential
from azure.storage.blob.aio import BlobServiceClient
async def main():
# Preferred: use async context manager for both credential and client
async with DefaultAzureCredential() as credential:
async with BlobServiceClient(
account_url="https://<account>.blob.core.windows.net",
credential=credential,
) as client:
# ... async operations
pass
```
> The async `get_bearer_token_provider` is at `azure.identity.aio.get_bearer_token_provider`.
## Sovereign Clouds
Use `AzureAuthorityHosts` or the `AZURE_AUTHORITY_HOST` env var:
```python
from azure.identity import DefaultAzureCredential, AzureAuthorityHosts
# Azure Government
credential = DefaultAzureCredential(authority=AzureAuthorityHosts.AZURE_GOVERNMENT)
# Azure China
credential = DefaultAzureCredential(authority=AzureAuthorityHosts.AZURE_CHINA)
```
| Constant | Authority |
|----------|-----------|
| `AzureAuthorityHosts.AZURE_PUBLIC_CLOUD` | `login.microsoftonline.com` (default) |
| `AzureAuthorityHosts.AZURE_GOVERNMENT` | `login.microsoftonline.us` |
| `AzureAuthorityHosts.AZURE_CHINA` | `login.chinacloudapi.cn` |
## Persistent Token Caching
Opt-in disk-based caching with `TokenCachePersistenceOptions`:
```python
from azure.identity import DefaultAzureCredential, TokenCachePersistenceOptions
credential = DefaultAzureCredential(
cache_persistence_options=TokenCachePersistenceOptions()
)
# Allow unencrypted fallback (NOT recommended for production)
credential = DefaultAzureCredential(
cache_persistence_options=TokenCachePersistenceOptions(allow_unencrypted_storage=True)
)
```
Storage: Windows (DPAPI), macOS (Keychain), Linux (Keyring).
## Multi-Tenant Support
Allow token acquisition for additional tenants beyond the configured one:
```python
from azure.identity import ClientSecretCredential
credential = ClientSecretCredential(
tenant_id="<home-tenant>",
client_id="<client-id>",
client_secret="<secret>",
additionally_allowed_tenants=["<other-tenant>", "*"], # "*" allows any tenant
)
```
## Error Handling
```python
from azure.identity import DefaultAzureCredential, CredentialUnavailableError
from azure.core.exceptions import ClientAuthenticationError
with DefaultAzureCredential() as credential:
try:
token = credential.get_token("https://management.azure.com/.default")
except CredentialUnavailableError:
# No credential in the chain could attempt authentication
pass
except ClientAuthenticationError as e:
# Authentication was attempted but failed
# e.message contains details from each credential in the chain
pass
```
## Logging
Enable authentication logging for debugging:
```python
import logging
# Enable verbose Azure Identity logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("azure.identity")
logger.setLevel(logging.DEBUG)
```
```bash
# Or via environment variable
AZURE_LOG_LEVEL=debug
```
## Credential Selection Matrix
| Environment | Recommended Credential |
|-------------|------------------------|
| Local Development | `DefaultAzureCredential` (uses Azure CLI) |
| Azure App Service | `DefaultAzureCredential` (uses Managed Identity) |
| Azure Functions | `DefaultAzureCredential` (uses Managed Identity) |
| Azure Kubernetes Service | `WorkloadIdentityCredential` |
| Azure VMs | `DefaultAzureCredential` (uses Managed Identity) |
| CI/CD Pipeline | `EnvironmentCredential` or `AzurePipelinesCredential` |
| Desktop App | `InteractiveBrowserCredential` |
| CLI / Headless Tool | `DeviceCodeCredential` |
| Middle-tier Service | `OnBehalfOfCredential` |
## Best Practices
1. **Pick sync OR async and stay consistent.** Do not mix `azure.xxx` sync clients with `azure.xxx.aio` async clients in the same call path. Choose one mode per module.
2. **Use credentials as context managers** (`with DefaultAzureCredential() as credential:`) when they own token caches / HTTP transports you want cleaned up; for async, use `async with` on credentials from `azure.identity.aio`.
3. **Use `DefaultAzureCredential`** for code that runs locally. Use a specific token credential for code that runs in Azure.
4. **Never hardcode credentials** — use environment variables or managed identity
5. **Prefer managed identity** in production Azure deployments
6. **Use `get_bearer_token_provider`** for non-Azure-SDK clients (OpenAI, REST APIs)
7. **Use `ChainedTokenCredential`** when you need a custom credential order
8. **Set `AZURE_CLIENT_ID`** for user-assigned managed identities (object ID and resource ID are also valid identifiers)
9. **Exclude unused credentials** to speed up `DefaultAzureCredential` authentication
10. **Use `CertificateCredential`** (not `ClientCertificateCredential` — that name doesn't exist)
11. **Enable `cache_persistence_options`** for long-running services to reduce token requests
12. **Reuse credential instances** — same credential can be shared across multiple clients
## Reference Links
| Resource | URL |
|----------|-----|
| PyPI Package | https://pypi.org/project/azure-identity/ |
| API Reference | https://learn.microsoft.com/python/api/azure-identity |
| GitHub Source | https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity |
| Credential Chains | https://aka.ms/azsdk/python/identity/credential-chains |
所有檔案
1 個檔案安裝 azure-identity-py
請下載並將技能檔案解壓縮至您的 .claude/skills/ 目錄中。
下載 ZIP複製儲存庫並將技能檔案複製到您的專案中。
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-python/skills/azure-identity-py # Copy SKILL.md to your .claude/skills/ directory
複製





首頁
