Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 57 ยท Identity and Governance

Managed Identities and Service Principals

Stop storing secrets in code: learn system- and user-assigned managed identities, service principals, and how DefaultAzureCredential picks a credential.

Every program that talks to Azure needs an identity. A person can sign in with a password and a second factor, but a web app or a background job cannot. The old answer was a secret: a client secret or connection string pasted into settings, copied to a build server, and eventually leaked into a repository. Secrets expire, get shared, and are hard to rotate.

Azure offers a better answer for code that runs inside Azure: the managed identity. Azure creates the identity, stores its credentials where your code cannot read them, and hands out short-lived tokens on request. Your code holds no secret at all. This lesson covers managed identities, how they relate to service principals, and the DefaultAzureCredential pattern the Azure SDKs use. The real services need an account, so their code is read-only. The runnable examples are Node.js stand-ins that model the credential chain and the token handling.

Service principals first

When you register an application in Microsoft Entra ID (see Microsoft Entra ID), the registration is the global definition of the app. In each tenant where the app is used, a service principal is created: the identity that actually receives role assignments. Think of the app registration as the class and the service principal as the instance that lives in your tenant.

A classic service principal authenticates with a client secret or a certificate. That works anywhere, including on a laptop or in another cloud, but you must store and rotate the credential yourself. A managed identity is a special service principal whose credential is managed entirely by Azure, so there is nothing to store and nothing to rotate.

Two kinds of managed identity

System-assigned User-assigned
Created Turned on for one resource Created as its own resource
Lifecycle Deleted with the resource Independent; you delete it
Sharing One resource only Attach to many resources
Good for A simple app that owns its identity Several resources that need identical access, or access that must exist before the resource does

Many resource types can have a managed identity: App Service, Azure Functions, virtual machines, Container Apps, AKS workloads and more. The CLI turns one on like this (read-only here):

Terminal
# System-assigned identity on a web app
az webapp identity assign --name my-app --resource-group web

# A user-assigned identity, then attach it
az identity create --name app-identity --resource-group web
az webapp identity assign --name my-app --resource-group web \
  --identities app-identity

Turning on an identity gives it no permissions. You still grant what it needs with a role assignment, exactly as in Role-Based Access Control:

Terminal
az role assignment create \
  --assignee <identity-principal-id> \
  --role "Storage Blob Data Reader" \
  --scope /subscriptions/<sub>/resourceGroups/web/providers/Microsoft.Storage/storageAccounts/mydata

Note the narrow data role and the narrow scope. Least privilege matters even more for identities that run unattended.

How a managed identity gets a token

Your code does not read a password. It asks a local metadata endpoint that Azure exposes to the host (a virtual machine uses a link-local address; App Service and Functions pass an endpoint and header through environment variables). That endpoint returns an access token for a requested resource, valid for a limited time. The SDK sends the token in an Authorization: Bearer ... header, and the target service checks the token and the identity's role assignments.

sequenceDiagram
    participant App as "Your code"
    participant MD as "Metadata endpoint on the host"
    participant Entra as "Microsoft Entra ID"
    participant Blob as "Blob Storage"
    App->>MD: "Token please, for storage"
    MD->>Entra: "Authenticate the managed identity"
    Entra-->>MD: "Access token with an expiry"
    MD-->>App: "Token"
    App->>Blob: "GET blob + Bearer token"
    Blob-->>App: "Data, if the role allows it"

The secret never leaves Azure. Your code only ever sees short-lived tokens.

The SDK also caches the token and asks for a new one shortly before it expires, so you do not manage lifetimes yourself.

DefaultAzureCredential

Developers do not want different code for their laptop, the CI server and production. The Azure SDKs (JavaScript, Python, .NET, Java and Go) provide DefaultAzureCredential, which tries several credential sources in order and uses the first one that works. The exact list and order differ slightly between SDKs and versions, but it generally covers:

  1. Environment variables for a service principal (AZURE_CLIENT_ID and friends).
  2. Workload identity, used by Kubernetes workloads.
  3. Managed identity, when running on an Azure host.
  4. Developer tools: an Azure CLI sign-in (az login), Azure PowerShell, Azure Developer CLI, or an editor sign-in.

A Node.js program using it (read-only here; it needs a storage account and the @azure/identity and @azure/storage-blob packages):

JavaScript
import { DefaultAzureCredential } from "@azure/identity";
import { BlobServiceClient } from "@azure/storage-blob";

const credential = new DefaultAzureCredential();
const service = new BlobServiceClient(
  "https://mydata.blob.core.windows.net",
  credential
);

const container = service.getContainerClient("reports");
for await (const blob of container.listBlobsFlat()) {
  console.log(blob.name);
}

There is no key and no connection string, only the account URL. The same file runs on your laptop (using your az login) and in production (using the managed identity). In Python the shape is the same:

Python
from azure.identity import DefaultAzureCredential
from azure.storage.blob import BlobServiceClient

service = BlobServiceClient(
    "https://mydata.blob.core.windows.net",
    credential=DefaultAzureCredential(),
)

If more than one identity is available you can steer the choice. For a user-assigned managed identity you pass its client ID; many teams also restrict the chain in production so a stray developer credential cannot be picked up by accident.

A credential chain: a stand-in

The real SDK talks to the machine and to Azure. The stand-in below keeps only the chain idea: each source either yields an identity or says it is unavailable, and the first success wins. Four invented situations show why the same program works everywhere, and what the failure message looks like when nothing is available.

Node.js Walk a credential chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last scenario is the classic production error: "it worked on my machine" because the laptop had an az login, while the server had no identity enabled or no role assigned. The real error message lists every credential that was tried, just as the stand-in does.

Token lifetime and caching: a stand-in

The second stand-in plays the role of the metadata service and shows why tokens make leaks less dangerous than secrets. A token expires, the client caches it, and a new one is requested slightly before the old one runs out. The one-hour lifetime and five-minute refresh window are invented numbers; real lifetimes and refresh behavior depend on the service and SDK.

Node.js Cache a short-lived token

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A stolen token is useful for minutes to hours, not forever, and it cannot be copied off the host by reading a settings file, because the settings file contains no credential.

Secretless access to Key Vault and Storage

Two services are the usual first targets:

  • Blob Storage with a data role such as Storage Blob Data Reader or Contributor. This replaces account keys and connection strings. See Storage Security and SAS Tokens.
  • Key Vault with a role such as Key Vault Secrets User, for the few secrets that still exist (third-party API keys, for instance). See Key Vault.

A tidy pattern is to give the app one identity, let it read secrets from Key Vault, and keep every other connection passwordless. Databases also support Entra authentication, so even database passwords can disappear.

Common mistakes

  • Enabling the identity but forgetting the role assignment. The result is a 403, not a failure to log in. Role assignments can take a few minutes to take effect.
  • Over-broad roles. Granting Contributor on the subscription to "make it work" defeats the point.
  • Using a system-assigned identity for a resource that is recreated often. Each recreation creates a new identity and loses its role assignments; a user-assigned identity avoids that.
  • Assuming it works outside Azure. A managed identity exists only on Azure hosts. On a laptop or another cloud, use your developer sign-in or workload identity federation (see CI/CD with GitHub Actions and Azure DevOps).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main advantage of a managed identity over a client secret?

    Azure holds and rotates the credential. Your code only receives short-lived tokens. You still need role assignments, and tokens do expire.
  2. 2. Which statement about user-assigned managed identities is correct?

    A user-assigned identity is its own resource with its own lifecycle and can be shared. System-assigned identities are tied to one resource.
  3. 3. Your app runs fine on your laptop but gets a 403 from Storage in production, where its managed identity is enabled. What is the most likely cause?

    Enabling an identity grants nothing. The laptop used your own account, which had access; the identity needs its own role assignment.
  4. 4. What does DefaultAzureCredential do?

    It is a chain: environment, workload identity, managed identity, developer tools and so on, so one program runs unchanged in several places.

Summary

  • An app registration defines an application; a service principal is its identity in a tenant and receives role assignments.
  • A managed identity is a service principal whose credential Azure manages; system-assigned ones follow one resource, user-assigned ones are standalone and shareable.
  • Code asks a local metadata endpoint for short-lived tokens, and SDKs cache and refresh them.
  • DefaultAzureCredential lets the same code use your sign-in locally and the managed identity in Azure.
  • Turning on an identity grants nothing: assign narrow roles at narrow scopes.
  • Use it for Storage, Key Vault and databases to remove secrets from code and settings.

Next: Azure Policy, Locks and Tags.