Skip to content
Visual explainer 3h to learn 5 steps

Connect an Azure app without embedded credentials

Use a managed identity to reach Storage or Key Vault with no secret in code or config.

By Invicly Tech, , in Microsoft Azure Cloud Engineering. About 13 minutes to read.

Topic 5 of 33

In short

A managed identity is an identity in Microsoft Entra ID that Azure creates and looks after for a resource such as an App Service app, a VM or a Container App. Your code asks the local Azure platform for a token instead of storing a password, connection string or key. You then give that identity an Azure role on the target, such as Key Vault Secrets User, so the app has exactly the access it needs.

Think of it like this: Instead of handing your app a copied office key, the building recognises the app by its staff badge and opens only the doors on its list.

Explained simply

Apps often need to talk to other services: read files from storage, fetch a password from a vault, or connect to a database. The old way was to paste a key or connection string into the app's settings. Those secrets leak, expire and are painful to rotate.

A managed identity removes that secret. Azure gives your app its own identity in Microsoft Entra ID and looks after the credentials behind it. When the app needs access, it asks the Azure platform it is running on for a short-lived token, and presents that token to the other service.

There are two kinds. A system-assigned identity is switched on for one resource, such as a web app, and is deleted when that resource is deleted. A user-assigned identity is a separate Azure resource that you create once and attach to one or more apps.

Having an identity does not grant any access on its own. You still give it a role on the target, such as Key Vault Secrets User on one vault. That keeps the app's access small and visible in the same place as everyone else's.

Press Play on a diagram to walk through it one step at a time.

SequenceApp Service reads a Key Vault secret with its managed identity
App code
Local identity endpoint
Microsoft Entra ID
Key Vault
  1. 1Ask for a token for vault.azure.net
    App code to Local identity endpoint: Ask for a token for vault.azure.net
  2. 2Request token for the app's identity
    Local identity endpoint to Microsoft Entra ID: Request token for the app's identity
  3. 3Return access token
    Microsoft Entra ID to Local identity endpoint: Return access token
  4. 4Hand back the token
    Local identity endpoint to App code: Hand back the token
  5. 5GET secret with bearer token
    App code to Key Vault: GET secret with bearer token
  6. 6Check RBAC, return secret value
    Key Vault to App code: Check RBAC, return secret value
FlowFrom secret in settings to managed identity
  1. 1
    Enable identity

    System- or user-assigned on the app

  2. 2
    Grant data role

    For example Key Vault Secrets User on one vault

  3. 3
    Change code

    Use DefaultAzureCredential and the vault URL

  4. 4
    Verify

    App reads the secret; logs show no 403

  5. 5
    Remove old secret

    Delete the connection string and rotate the old key

In depth

System-assigned or user-assigned

A system-assigned identity is the simplest choice: one switch on the resource, one principal, gone when the resource goes. That clean lifecycle is also its weakness. If you delete and recreate the app, for example during a redeploy from scratch, you get a brand new principal with no role assignments.

A user-assigned identity is a resource of type Microsoft.ManagedIdentity/userAssignedIdentities. You create it first, grant it roles, then attach it to apps. It survives app rebuilds and can be shared, for example by every replica in a scale set or by several Container Apps that pull from the same registry. Creating the identity and its roles before the app also avoids a startup race where the app runs before its access exists. The trade-off is that sharing one identity across many apps widens what a single compromised app can reach, so share only when the apps truly need the same access.

CompareChoosing an identity type
System-assigned
  • Created by enabling it on one resource
  • Deleted with that resource
  • Cannot be shared
  • Simple for a single app
User-assigned
  • Standalone resource you create first
  • Survives app rebuilds
  • Can be attached to many resources
  • Roles can exist before the app starts

Where the token comes from

Your code never sees a password. On a VM, it calls the Instance Metadata Service at the link-local address 169.254.169.254, which is reachable only from inside that VM. On App Service and Azure Functions, the platform sets IDENTITY_ENDPOINT and IDENTITY_HEADER environment variables that point to a local token service. Container Apps work the same way.

The request names the resource the token is for, such as https://vault.azure.net for Key Vault or https://storage.azure.com for Storage. The local endpoint gets a token from Microsoft Entra ID for the identity and returns it. The app sends it as a bearer token, and the target service checks the signature and the caller's role assignments. You rarely write these calls yourself: the Azure Identity libraries handle the request, caching and refresh.

  • VMs: Instance Metadata Service at 169.254.169.254
  • App Service and Functions: IDENTITY_ENDPOINT and IDENTITY_HEADER
  • Token audience names the target service
  • Azure Identity libraries cache and refresh tokens

Granting data access: Storage and Key Vault

Give the identity a data-plane role at the narrowest useful scope. For Blob Storage, Storage Blob Data Reader allows reading blobs and Storage Blob Data Contributor allows writing too; you can scope them to a single container. For Key Vault using the Azure RBAC permission model, which Microsoft recommends over the older access policies, Key Vault Secrets User lets the app read secret values, while Key Vault Secrets Officer can create and change secrets and suits a person or pipeline, not the app.

If your vault still uses access policies, role assignments have no effect on data access; you would add an access policy instead, or switch the vault to RBAC after recreating the needed grants. Once the identity has the role, remove any old connection string or key from app settings. For Storage, you can then disable shared key access on the account so keys cannot be used at all.

  • Storage Blob Data Reader: read blobs
  • Key Vault Secrets User: read secret values
  • Scope to one vault, account or container
  • Remove old keys from settings once identity works

DefaultAzureCredential and local development

DefaultAzureCredential tries a chain of credential types in order and uses the first that works. In Python the chain starts with environment variables, then workload identity, then managed identity, and later developer tools such as the Azure CLI, Azure PowerShell and Azure Developer CLI. In Azure the managed identity is found; on your laptop your az login is used. The same code runs in both places.

Two details matter. If the app has a user-assigned identity, tell the credential which one, by passing managed_identity_client_id or setting AZURE_CLIENT_ID. And for production, Microsoft suggests a specific credential such as ManagedIdentityCredential, because a predictable credential is easier to debug and avoids slow fallbacks. Locally, your own user needs the same data role on the vault or storage account, ideally through a developer group, so you test real permissions rather than an admin's.

Replacing identities and cached tokens

Plan for the identity changing. If you recreate a resource with a system-assigned identity, its principal ID changes, old role assignments point at a deleted principal, and the app fails with 403. Store role assignments in the same template as the app, or use a user-assigned identity, so a rebuild restores access automatically. Clean up orphaned assignments, which the portal shows as Identity not found.

Token caching also affects changes. Apps cache tokens until shortly before they expire, and Microsoft documents that managed identity back-end services cache tokens per target resource for around 24 hours. So adding the identity to a group, or removing a role, may not take effect straight away. For urgent revocation, remove the identity from the resource or disable the app, and grant roles directly rather than through groups when changes must apply quickly.

Learn it in 5 short steps

About 35m each. Track them with a timer in your plan.

  1. 1
    Compare system- and user-assigned identities~35m
  2. 2
    Follow the token flow~35m
  3. 3
    Grant the identity a data role~35m
  4. 4
    Read a Key Vault secret~35m
  5. 5
    Plan for identity replacement~35m

Key points

  • System-assigned identities are created with a resource and deleted with it; user-assigned identities are separate resources you can share.
  • The platform rotates the underlying credentials for you; no secret appears in code or app settings.
  • An identity can do nothing until you assign it a role on the target, usually a data-plane role.
  • DefaultAzureCredential uses your developer sign-in locally and the managed identity in Azure, with the same code.
  • Replacing a system-assigned identity creates a new principal, so its role assignments must be recreated.

Key terms

Tap a card to flip it. 0/6 known

Examples

python
# pip install azure-identity azure-keyvault-secrets
import os
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient

vault_url = os.environ["KEY_VAULT_URL"]  # https://kv-lab-api.vault.azure.net/
credential = DefaultAzureCredential()
client = SecretClient(vault_url=vault_url, credential=credential)

secret = client.get_secret("payments-api-key")
print("Read secret, length:", len(secret.value))

The same code works on your laptop (Azure CLI sign-in) and in Azure (managed identity).

App Service reads a Key Vault secret with no secret in config

Prerequisites: an App Service app (a Basic plan is enough; check current pricing), a key vault using the Azure RBAC permission model, and Owner or an access-admin role on the vault. Steps: enable the system-assigned identity, grant it Key Vault Secrets User on the vault, and set only the vault URL as an app setting. The app uses the Python code from the explainer. Evidence: the app logs show the secret was read, and the vault's role assignments list the app's principal. Rollback: delete the role assignment, then the lab resource group.

bash
PRINCIPAL=$(az webapp identity assign -g rg-lab-api -n app-lab-api \
  --query principalId -o tsv)
KV_ID=$(az keyvault show -g rg-lab-api -n kv-lab-api --query id -o tsv)

az role assignment create --assignee-object-id "$PRINCIPAL" \
  --assignee-principal-type ServicePrincipal \
  --role "Key Vault Secrets User" --scope "$KV_ID"

az webapp config appsettings set -g rg-lab-api -n app-lab-api \
  --settings KEY_VAULT_URL=https://kv-lab-api.vault.azure.net/

A user-assigned identity for blob uploads, tested locally first

A worker uploads reports to Blob Storage. The team creates a user-assigned identity id-report-worker and grants it Storage Blob Data Contributor on the reports container only. Before deploying, a developer with the same role on that container runs the code locally after az login, which proves the permissions with no Azure compute cost. In Azure, the app sets AZURE_CLIENT_ID to the identity's client ID so DefaultAzureCredential picks the right identity. Evidence: the blob appears in the container. A free local alternative for the storage side is the Azurite emulator, though it uses its own keys rather than Entra tokens.

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

account_url = os.environ["STORAGE_URL"]  # https://stlabapi01.blob.core.windows.net
credential = DefaultAzureCredential()  # uses AZURE_CLIENT_ID in Azure if set
service = BlobServiceClient(account_url, credential=credential)

blob = service.get_blob_client(container="reports", blob="daily-2026-12-01.csv")
blob.upload_blob(b"order_id,total\n1001,25.00\n", overwrite=True)
print("Uploaded", blob.url)

Quick reference

  • System-assigned: tied to one resource. User-assigned: standalone, reusable, survives rebuilds.
  • An identity has no access until you assign it a role on the target.
  • Key Vault Secrets User reads secret values; Secrets Officer manages them.
  • Storage Blob Data Reader or Contributor gives blob access; scope it to a container if you can.
  • az webapp identity assign -g RG -n APP returns the principalId to use in role assignments.
  • Set AZURE_CLIENT_ID when an app has a user-assigned identity and uses DefaultAzureCredential.
  • Recreating a system-assigned identity creates a new principal; role assignments must be recreated.

Common mistakes

  • Enabling the identity but forgetting the role assignment, then reading a 403 Forbidden as a network problem.
  • Granting Key Vault Administrator or Owner when the app only needs Key Vault Secrets User.
  • Deleting and recreating a resource with a system-assigned identity and losing all of its access silently.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What does a managed identity remove from your app?

Question 2

2Several Container Apps must pull from the same registry, and the access must exist before they start. Which identity fits best?

Question 3

3On an Azure VM, where does the app request a managed identity token?

Question 4

4An app was deleted and redeployed and now gets 403 from Key Vault. Its code is unchanged. What happened?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    For each case say system- or user-assigned and why: a single web app reading one vault; ten VMs in a scale set reading the same storage container; a Container App that must pull its image at first start.

  2. Exercise 2medium

    Without any Azure compute, prove your code path locally: create a key vault in your lab group with RBAC, give your own user Key Vault Secrets Officer, add a secret, then run the explainer's Python code after az login. Expected evidence: the script prints the secret length. Cleanup: delete the group and purge the vault.

  3. Exercise 3hard

    Write a migration plan for an app whose Storage connection string sits in app settings, ending with shared key access disabled. Include verification and rollback.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do managed identities cost anything?
No. There is no charge for the identity itself; you pay only for the resources that use it.
Can I use a managed identity from my laptop?
No. Tokens are only issued to code running on the Azure resource. Locally, DefaultAzureCredential uses your own sign-in, such as az login, with the same code.
Do I need to rotate a managed identity's credentials?
No. Azure rotates the underlying credentials automatically. You only manage which roles the identity has.
Can a managed identity reach services outside Azure?
Only services that accept Microsoft Entra tokens. Some can trust it through workload identity federation; others still need a secret, which you would keep in Key Vault.

Go deeper

ShareXLinkedInWhatsApp