Managed identities and DefaultAzureCredential

Microsoft Azure · Practical · 12 min

Managed identities remove connection strings and client secrets, the most common cloud credential leak.

A managed identity is a service principal whose credentials Azure creates, stores and rotates for you. Code running on the resource asks the local platform endpoint (the Instance Metadata Service on VMs, an equivalent endpoint on App Service, Functions, Container Apps) for a token and never sees a secret.

Two kinds:

  • System-assigned: created with, and deleted with, one resource. Simple, one identity per resource.
  • User-assigned: a standalone resource (Microsoft.ManagedIdentity/userAssignedIdentities) you attach to many resources. Survives redeployments, can be granted roles before the app exists, and can hold federated credentials. Prefer it for production and IaC.

The workflow: enable the identity, grant it a role on the target (Key Vault Secrets User, Storage Blob Data Contributor, a database user), then use the Azure SDK.

In code, use `DefaultAzureCredential` from azure-identity. It tries a chain of sources: environment variables, workload identity, managed identity, then developer logins such as the Azure CLI. The same code works on your laptop (as you) and in Azure (as the identity). For a user-assigned identity set AZURE_CLIENT_ID so the right one is picked when several are attached. In production you can use ManagedIdentityCredential directly for faster, more predictable startup.

Example

# pip install azure-identity azure-storage-blob
from azure.identity import DefaultAzureCredential
from azure.storage.blob import BlobServiceClient

# Locally: uses your `az login`. In Azure: uses the managed identity.
cred = DefaultAzureCredential()
svc = BlobServiceClient("https://stordersprod01.blob.core.windows.net", credential=cred)

for blob in svc.get_container_client("invoices").list_blobs(name_starts_with="2026/10/"):
    print(blob.name)   # 2026/10/inv-1001.pdf

# Setup (bash):
# az webapp identity assign -g rg-web -n orders-web
# az role assignment create --assignee <principalId> \
#   --role "Storage Blob Data Reader" --scope <storage account id>

Remember

  • Managed identity = Azure-managed credentials, no secrets in config
  • System-assigned lives and dies with its resource; user-assigned is reusable
  • Still needs a role assignment on the target
  • DefaultAzureCredential runs unchanged locally and in Azure

Watch out for

  • Enabling the identity but forgetting the role assignment, then getting 403 errors.

Check yourself

  1. Why choose a user-assigned identity for an app deployed with IaC?
  2. On a developer laptop, which credential does DefaultAzureCredential typically end up using?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: learn.microsoft.com/en-us/entra/identity/managed-identities-azure-resources/overview