AZ

azure-identity-py

Authenticate Python applications with Azure services securely. Manage identities and tokens using the official Azure Identity SDK.

Install

mkdir -p .claude/skills/azure-identity-py && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/5463" && unzip -o skill.zip -d .claude/skills/azure-identity-py && rm skill.zip

Installs to .claude/skills/azure-identity-py

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Azure Identity SDK for Python authentication with Microsoft Entra ID. Use for DefaultAzureCredential, managed identity, service principals, and token caching. Triggers: "azure-identity", "DefaultAzureCredential", "authentication", "managed identity", "service principal", "credential".
285 chars✓ has a “when” triggerlonger than Claude Code's old 250-char listing cap (fine on current versions)
Intermediate

Key capabilities

  • Authenticate via DefaultAzureCredential
  • Implement managed identity authentication
  • Configure service principal credentials
  • Acquire bearer tokens for non-Azure SDKs

How it works

The library provides a chain of credential types that automatically detect the environment to acquire tokens for Azure resources.

Inputs & outputs

You give it
Authentication request
You get back
Bearer token

When to use azure-identity-py

  • Authenticate Azure SDK clients with managed identity
  • Configure service principal authentication
  • Cache authentication tokens in Python apps

About this skill

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

pip install azure-identity

For VS Code or broker-based desktop auth:

pip install azure-identity-broker

Python Version

azure-identity supports Python 3.9+.

Environment Variables

# 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

Authentication & Lifecycle

🔑 Two rules apply to every code sample below:

  1. Prefer DefaultAzureCredential. It works locally (Azure CLI / VS Code / Developer CLI) and in Azure (managed identity, workload identity) with no code change. Avoid connection strings, account/API keys — they bypass Entra audit and rotation.
    • Local dev: DefaultAzureCredential works as-is.
    • Production: set AZURE_TOKEN_CREDENTIALS=prod (or AZURE_TOKEN_CREDENTIALS=<specific_credential>) to constrain the credential chain to production-safe credentials.
  2. Wrap credentials and clients in context managers when they own token caches / transports:
    • Sync: with DefaultAzureCredential() as credential:
    • Async: async with DefaultAzureCredential() as credential: (from azure.identity.aio)

Snippets may abbreviate this setup, but production code should always follow both rules.

DefaultAzureCredential

The recommended credential for most scenarios. Tries multiple authentication methods in order:

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 for the current credential chain order and defaults.

Customizing DefaultAzureCredential

# 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

ParameterDefaultEffect
exclude_environment_credentialFalseSkip env-var-based auth
exclude_workload_identity_credentialFalseSkip Kubernetes workload identity
exclude_managed_identity_credentialFalseSkip managed identity
exclude_shared_token_cache_credentialFalseSkip shared token cache
exclude_visual_studio_code_credentialFalseSkip VS Code credential
exclude_cli_credentialFalseSkip Azure CLI
exclude_powershell_credentialFalseSkip Azure PowerShell
exclude_developer_cli_credentialFalseSkip Azure Developer CLI
exclude_interactive_browser_credentialTrueSkip interactive browser
exclude_broker_credentialFalseSkip 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:

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

CredentialUse Case
DefaultAzureCredentialMost scenarios — auto-detects environment
ChainedTokenCredentialCustom credential chain with explicit ordering

Azure-Hosted Applications

CredentialUse Case
EnvironmentCredentialAuth via AZURE_CLIENT_SECRET / AZURE_CLIENT_CERTIFICATE_PATH env vars
ManagedIdentityCredentialAzure VMs, App Service, Functions, AKS, Arc, Service Fabric
WorkloadIdentityCredentialKubernetes with Microsoft Entra Workload ID

Service Principals

CredentialUse Case
ClientSecretCredentialService principal with client secret
CertificateCredentialService principal with PEM/PKCS12 certificate
ClientAssertionCredentialService principal with signed JWT assertion
AzurePipelinesCredentialAzure Pipelines with workload identity federation
OnBehalfOfCredentialMiddle-tier on-behalf-of flow (delegated user identity)

User Authentication

CredentialUse Case
InteractiveBrowserCredentialInteractive browser OAuth sign-in
DeviceCodeCredentialHeadless/SSH device code flow
AuthorizationCodeCredentialPreviously obtained authorization code

Developer Tools

CredentialUse Case
AzureCliCredentialaz login
AzureDeveloperCliCredentialazd auth login
AzurePowerShellCredentialConnect-AzAccount
VisualStudioCodeCredentialVS Code Azure Resources extension

Specific Credential Examples

ManagedIdentityCredential

For Azure-hosted resources (VMs, 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="<user-assigned-mi-client-id>"
)
# Also valid:
# credential = ManagedIdentityCredential(object_id="<object-id>")
# credential = ManagedIdentityCredential(resource_id="<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

Note: The class is CertificateCredential, NOT ClientCertificateCredential.

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

from azure.identity import AzureCliCredential

credential = AzureCliCredential()
# With tenant restriction
credential = AzureCliCredential(tenant_id="<tenant-id>")

ChainedTokenCredential

Custom credential chain:

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:

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):

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:

from azure.i

---

*Content truncated.*

When not to use it

  • When hardcoding credentials is required
  • When using non-Entra ID authentication methods

Prerequisites

azure-identity

Limitations

  • Requires Python 3.9+
  • Interactive browser credential disabled by default

How it compares

It abstracts authentication flows into a single credential chain, removing the need for environment-specific code.

Compared to similar skills

azure-identity-py side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
azure-identity-py (this skill)129dReviewIntermediate
cloudbase-guidelines13moNo flagsIntermediate
create-python-x402-server04moReviewAdvanced
fastapi-templates5202moNo flagsIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

More by microsoft

View all by microsoft

You might also like

cloudbase-guidelines

TencentCloudBase

Essential CloudBase (TCB, Tencent CloudBase, 云开发, 微信云开发) development guidelines. MUST read when working with CloudBase projects, developing web apps, mini programs, or backend services using CloudBase platform.

17

create-python-x402-server

manne1086

Create x402 payment-protected servers with FastAPI (async) or Flask (sync) for Algorand. Use when building resource servers that require USDC payments, setting up payment middleware, configuring route pricing, or protecting API endpoints with x402. Strong triggers include "create a FastAPI server wi

00

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

5201,086

architecture-patterns

wshobson

Implement proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design. Use when architecting complex backend systems or refactoring existing applications for better maintainability.

55214

fastapi-pro

sickn33

Build high-performance async APIs with FastAPI, SQLAlchemy 2.0, and Pydantic V2. Master microservices, WebSockets, and modern Python async patterns. Use PROACTIVELY for FastAPI development, async optimization, or API architecture.

79181

telegram-bot-builder

davila7

Expert in building Telegram bots that solve real problems - from simple automation to complex AI-powered bots. Covers bot architecture, the Telegram Bot API, user experience, monetization strategies, and scaling bots to thousands of users. Use when: telegram bot, bot api, telegram automation, chat bot telegram, tg bot.

106130

Search skills

Search the agent skills registry