Managed Identities and Service Principals
-
Phase 0: Before you start
-
Phase 1: The foundation
-
Phase 2: Day-to-day operations
-
Phase 3: Enterprise architecture
-
Phase 4: Troubleshooting step by step
-
Phase 5: Final project and career
An Azure managed identity gives a script, VM or app an identity of its own in Entra ID, and there’s no password or key for you to keep anywhere. Azure creates the credential, rotates it and hands the app a token whenever it asks for one.
Before managed identities came along, apps used service principals with client secrets, which is a password in a config file that expires, gets copied onto laptops and sooner or later lands in Git. You’ll make one of those as well, so you can see what you’re getting away from.
In the lab, a tiny container reads a file from a storage account with nothing but a managed identity. After that you’ll break it in the two ways behind most “it worked yesterday” tickets.
| Time | You need | Cost | By the end you can |
|---|---|---|---|
| About 45 minutes | The CLI, signed in as the account owner | About USD 0.02 (a small storage account and a container that runs for a minute) | Create a service principal and a managed identity, give them roles, and tell their failures apart |
What it is, in one line
A managed identity is an Entra ID identity that Azure owns and looks after for your resource, so your code can sign in with no password at all.
In Simple Words
A staff badge instead of a borrowed key
Say a delivery robot has to get into the school store room. You could give it a copy of the caretaker’s key, but keys get copied and lost, and after a while nobody remembers who has one.
It’s better if the school gives the robot a staff badge of its own. The door reads the badge, the office decides which doors it opens, and the badge renews itself each day, so nobody ever handles a key.
In Azure terms, the copied key is a client secret and the badge is a managed identity.
Engineer's View
Three kinds of non-human identity
- Service principal with a secret or certificate: made from an app registration. You get an app (client) ID and a secret, and storing and rotating that secret is your job. By default the CLI’s
az ad sp create-for-rbacgives you a secret that’s valid for one year. It works from anywhere, outside Azure too. - System-assigned managed identity: switched on for one resource (a VM, web app or function). It’s created and deleted along with that resource, and you can’t share it.
- User-assigned managed identity: a resource in its own right (
Microsoft.ManagedIdentity/userAssignedIdentities) that you can attach to lots of resources. It stays when they’re deleted, so its role assignments don’t change when you rebuild things.
Inside Azure, your code asks a local endpoint for a token. On a VM that’s the Instance Metadata Service at 169.254.169.254, and containers and app services have their own versions of it. The secret never reaches your code or the disk.
Managed identities and service principals count as workload identities, so mandatory MFA doesn’t cover them, and what protects them is giving them least-privilege roles.
Each identity has two IDs that people mix up all the time. You sign in with the client ID (app ID), and role assignments point at the object ID (principal ID).
If you get “PrincipalNotFound” straight after creating an identity, it’s usually replication delay, so wait a minute and try again, or pass --assignee-principal-type ServicePrincipal.
How it works, step by step
This is what goes on when the lab’s container reads a blob using its managed identity:
- The container starts up with the user-assigned identity attached.
- The code (the Azure CLI in this case) calls the local identity endpoint and asks for an Azure Storage token, giving the identity’s client ID.
- Azure hands back a short-lived token for that identity, signed by Entra ID.
- The code sends the token to the storage account’s blob endpoint.
- Storage checks RBAC to see whether this identity has a data role, like Storage Blob Data Reader, on the account or the container, and if it does, it returns the list.
The identity proves who the code is, and RBAC still decides what it’s allowed to do. A managed identity without a role can sign in perfectly well and still get refused everything.
So for anything running in Azure, start with a managed identity, the smallest role and the smallest scope. Service principals with secrets are for things outside Azure that can’t use federated credentials, and each one needs an owner, an expiry date and a plan for rotating it.
Hands-on lab: read storage with no secret
Before you run any command, double-check it
Read every command twice before you press Enter. Check the target: the system or account, the IDs, the names and the sizes. These commands are for learning and were tested in our lab, not on your system. At work, run the read-only list commands first, follow your change process, make sure a backup exists, and ask a second person to check anything that changes or deletes data. You run them at your own risk.
You’ll set up a storage account with one file in it, read it with a service principal, and then read it again with a managed identity from a container. Run all of it in your admin PowerShell window.
1Create a storage account with one file
Run this:
$rgName = 'rg-saat-l10'
az group create --name $rgName --tags course=saatvedha-azure lesson=10 -o none
$st = 'stsaat10' + (Get-Random -Maximum 999999)
az storage account create --name $st --resource-group $rgName --sku Standard_LRS --kind StorageV2 --allow-blob-public-access false --tags course=saatvedha-azure lesson=10 -o none
$stId = az storage account show --name $st --resource-group $rgName --query id -o tsv
$me = az ad signed-in-user show --query id -o tsv
az role assignment create --assignee-object-id $me --assignee-principal-type User --role "Storage Blob Data Contributor" --scope $stId -o none
'Quarterly report: all good.' | Set-Content C:\azure-lab\hello.txt
Start-Sleep -Seconds 60
az storage container create --name reports --account-name $st --auth-mode login -o none
az storage blob upload --container-name reports --name hello.txt --file C:\azure-lab\hello.txt --account-name $st --auth-mode login -o none
az storage blob list --container-name reports --account-name $st --auth-mode login --query "[].name" -o tsvYou should see this:
hello.txtAs you saw in Lesson 7, even an Owner needs a data role here. The 60-second pause gives the new role time to take effect.
2The old way: a service principal with a secret
Run this:
$sp = az ad sp create-for-rbac --name sp-saat-l10 --role "Storage Blob Data Reader" --scopes $stId | ConvertFrom-Json
$sp | Select-Object appId, displayName, tenantYou should see something like this:
WARNING: The output includes credentials that you must protect. Be sure that you do not include these credentials in your code or check the credentials into your source control. For more information, see https://aka.ms/azadsp-cli
appId displayName tenant
----- ----------- ------
4f3e2d1c-0b9a-4876-a5b4-c3d2e1f0a9b8 sp-saat-l10 9a8b7c6d-1e2f-4a3b-8c9d-0e1f2a3b4c5dThe secret sits in $sp.password, and that one string now opens your data for a whole year. Sign in with it in a separate CLI session and try it:
$env:AZURE_CONFIG_DIR = 'C:\azure-lab\sp-cli'
az login --service-principal --username $sp.appId --password $sp.password --tenant $sp.tenant --allow-no-subscriptions -o none
az storage blob list --container-name reports --account-name $st --auth-mode login --query "[].name" -o tsv
az logout
Remove-Item Env:AZURE_CONFIG_DIRYou should see this:
hello.txt3The better way: a user-assigned managed identity
Run this:
$id = az identity create --name id-saat-l10 --resource-group $rgName --tags course=saatvedha-azure lesson=10 | ConvertFrom-Json
$id | Select-Object name, clientId, principalId
az role assignment create --assignee-object-id $id.principalId --assignee-principal-type ServicePrincipal --role "Storage Blob Data Reader" --scope $stId -o noneYou should see something like this:
name clientId principalId
---- -------- -----------
id-saat-l10 7d6c5b4a-3928-4170-8e6f-5d4c3b2a1908 e1d2c3b4-a596-4877-8695-a4b3c2d1e0f9Look at what isn’t there: no password and nothing to store. You sign in with clientId, and the role points at principalId (the object ID).
4Let a container use the identity
Container Instances needs its resource provider registered, once per subscription, so run this:
az provider register --namespace Microsoft.ContainerInstance --wait
az provider show --namespace Microsoft.ContainerInstance --query registrationState -o tsvYou should see this:
RegisteredNext, write the command the container will run, then start it:
$cmd = '/bin/sh -c "az login --identity --client-id CLIENTID --allow-no-subscriptions -o none && az storage blob list --account-name ACCOUNT --container-name reports --auth-mode login --query [].name -o tsv"'
$cmd.Replace('CLIENTID', $id.clientId).Replace('ACCOUNT', $st) | Set-Content C:\azure-lab\mi-test.txt
az container create --resource-group $rgName --name aci-saat-l10 --image mcr.microsoft.com/azure-cli:latest --os-type Linux --cpu 1 --memory 1.5 --restart-policy Never --assign-identity $id.id --command-line "@C:\azure-lab\mi-test.txt" --tags course=saatvedha-azure lesson=10 -o none
do { Start-Sleep 10; $state = az container show -g $rgName -n aci-saat-l10 --query "containers[0].instanceView.currentState.state" -o tsv; $state } while ($state -ne 'Terminated')
az container logs --resource-group $rgName --name aci-saat-l10You should see something like this:
Waiting
Running
Terminated
hello.txtThe container signed in as id-saat-l10 and listed the file, and there’s no secret anywhere, not in the command file and not in the container settings. Passing the command with @file keeps PowerShell away from its quotes and &&.

✅ Checkpoint: Both the service principal and the managed identity listed hello.txt, and the container’s command file contains no secret.
Break It, Then Fix It
To the app, these two failures look the same (“can’t read storage”), but the causes and fixes have nothing in common.
1Break it: a wrong or old client secret
Run this:
$env:AZURE_CONFIG_DIR = 'C:\azure-lab\sp-cli'
az login --service-principal --username $sp.appId --password 'not-the-real-secret' --tenant $sp.tenant --allow-no-subscriptionsYou’ll get an error like this:
AADSTS7000215: Invalid client secret provided. Ensure the secret being sent in the request is the client secret value,
not the client secret ID, for a secret added to app '4f3e2d1c-0b9a-4876-a5b4-c3d2e1f0a9b8'.You get the same error when a secret expires and someone pastes in the old one, or when someone copies the secret’s ID from the portal instead of its value. Entra ID wouldn’t issue a token, so the request never got as far as storage.
Fix it by using the real secret, then delete the service principal, since this course doesn’t use secrets again.
Remove-Item Env:AZURE_CONFIG_DIR
Remove-Item C:\azure-lab\sp-cli -Recurse -Force -ErrorAction SilentlyContinue
az ad app delete --id $sp.appId
$sp = $nullDeleting the app registration removes its service principal and secret with it, and setting $sp to null clears the secret out of your PowerShell session.
2Break it: a managed identity with no role
Create a second identity and attach it to a new container, but leave out the role assignment:
$id2 = az identity create --name id-saat-l10-norole --resource-group $rgName --tags course=saatvedha-azure lesson=10 | ConvertFrom-Json
$cmd.Replace('CLIENTID', $id2.clientId).Replace('ACCOUNT', $st) | Set-Content C:\azure-lab\mi-test2.txt
az container create --resource-group $rgName --name aci-saat-l10b --image mcr.microsoft.com/azure-cli:latest --os-type Linux --cpu 1 --memory 1.5 --restart-policy Never --assign-identity $id2.id --command-line "@C:\azure-lab\mi-test2.txt" --tags course=saatvedha-azure lesson=10 -o none
do { Start-Sleep 10; $state = az container show -g $rgName -n aci-saat-l10b --query "containers[0].instanceView.currentState.state" -o tsv } while ($state -ne 'Terminated')
az container logs --resource-group $rgName --name aci-saat-l10bYou’ll get output like this:
You do not have the required permissions needed to perform this operation.
Depending on your operation, you may need to be assigned one of the following roles:
"Storage Blob Data Owner"
"Storage Blob Data Contributor"
"Storage Blob Data Reader"
...This time the sign-in worked. az login --identity succeeded because the identity exists, and then storage turned the request down because the identity has no data role. “Token OK, permission missing” is the managed identity problem you’ll see most often at work.
To fix it, give the role, wait a minute and run the same container again:
az role assignment create --assignee-object-id $id2.principalId --assignee-principal-type ServicePrincipal --role "Storage Blob Data Reader" --scope $stId -o none
Start-Sleep -Seconds 60
az container start --resource-group $rgName --name aci-saat-l10b
az container logs --resource-group $rgName --name aci-saat-l10bYou should see this:
hello.txt
3Clean up
Run this:
$stId | ForEach-Object { az role assignment delete --scope $_ }
az group delete --name $rgName --yes
C:\azure-lab\Find-LabResources.ps1You should see this:
Nothing tagged course=saatvedha-azure is left.Deleting the resource group gets rid of both user-assigned identities and the containers. You removed the role assignments on the storage account first, so there are no orphaned “Identity not found” entries left over.
✅ Checkpoint: Both failures reproduced and fixed, the service principal is deleted, and nothing tagged for the course is left.
This happened at work
The secret that expired on a public holiday
A bank had a nightly job that copied card-transaction files from a partner’s SFTP server into Azure Storage. It ran on an on-premises server and signed in as a service principal, with the client secret sitting in a config file. An engineer who’d since left the company had created that secret with the default one-year expiry.
The secret expired on a public holiday. For three nights the job failed with AADSTS7000215, but it only wrote the errors to a local log that nobody looked at. On the fourth morning the settlement reports were missing and the reconciliation team escalated it.
Making a new secret took two minutes, and finding everywhere the old one was used took most of the day.
What they changed: the job moved to an Azure VM with a user-assigned managed identity, so there’s no secret at all now. For the few apps that have to run outside Azure, secrets were swapped for federated credentials or certificates kept in Key Vault, each with a named owner. A weekly script lists any app registration whose credential expires in the next 60 days and raises a ticket for its owner.
Common mistakes and troubleshooting
| Mistake | What you see | What to do |
|---|---|---|
| Storing a client secret in code or config | Leaked or expired secrets, AADSTS7000215 | Inside Azure, use a managed identity. Outside it, use Key Vault and certificates. |
| Pasting the secret ID instead of the value | AADSTS7000215 | Copy the Value column when you create the secret, because it’s only shown once. |
| Giving the role to the client ID | PrincipalNotFound or nothing works | Role assignments use the object (principal) ID. |
| Assigning a role right after creating the identity | PrincipalNotFound | Wait a minute, or pass --assignee-principal-type ServicePrincipal. |
| System-assigned identity on resources you rebuild often | Roles lost after every rebuild | Use a user-assigned identity, because it outlives the resource. |
| Forgetting the data role | Sign-in works, data access is refused | Add a data role such as Storage Blob Data Reader at the smallest scope. |
Interview questions
Click a question to open it. Each one is worded the way an interviewer would put it, and underneath you’ll find why they ask it and one way you could answer in your own words.
Fresher level
1. What is a managed identity, and why use one?
Why they ask this: A basic modern-Azure concept.
How you might answer: It’s an identity in Entra ID that Azure creates and looks after for a resource such as a VM or a container. The code picks up tokens from a local endpoint, so you’ve got no password or key to store, rotate or leak.
2. What’s the difference between system-assigned and user-assigned managed identities?
Why they ask this: A frequent exam and interview question.
How you might answer: A system-assigned one belongs to a single resource and goes when that resource is deleted. A user-assigned one is a resource of its own, you can attach it to several resources, and it stays when they’re deleted, so its role assignments survive rebuilds.
3. What are the client ID and the object ID of an identity used for?
Why they ask this: They want to see you won’t mix them up in scripts.
How you might answer: You sign in with the client ID, which is also called the app ID. Role assignments point to the object ID, which you’ll also see called the principal ID.
2–5 years experience
4. An app with a managed identity can’t read a storage account. How do you troubleshoot it?
Why they ask this: They want a clear split between sign-in problems and permission problems.
How you might answer: First I’d check whether it can get a token at all. If az login --identity or the SDK call fails, the problem is the identity setup, like a wrong client ID or the identity not being attached. If the token’s fine and storage still refuses, it’s RBAC, so I’d look for a data role on the account or container and make sure it points at the right principal ID. And I keep in mind that a new role assignment can take a few minutes.
5. A nightly job suddenly fails with AADSTS7000215. What happened?
Why they ask this: They’re checking that you recognise an expired or wrong secret.
How you might answer: That’s an invalid client secret, most often because it expired or someone saved the secret ID instead of the value. I’d create a new secret and update everywhere it’s used, and then plan to get rid of the secret altogether with a managed identity or a federated credential.
6. When would you still use a service principal with a certificate or secret?
Why they ask this: They want balanced judgement, not “never”.
How you might answer: When the workload runs outside Azure and can’t use workload identity federation, an old on-premises tool for example. Even then I’d go for a certificate in a secure store over a secret, give it the narrowest role possible, and track its expiry with a named owner.
Senior level
7. How would you find and reduce long-lived secrets across a tenant?
Why they ask this: They want a concrete governance plan.
How you might answer: I’d pull every app registration with a password or certificate credential, plus its expiry date, through Microsoft Graph, and match each one to an owner and the sign-in logs. The unused ones get removed, the Azure-hosted ones move to managed identities, and the external ones move to federated credentials where that’s possible. After that, a policy and a regular report stop new long-lived secrets from creeping in unnoticed.
8. Design identity for twenty microservices that each need different storage and Key Vault access.
Why they ask this: They want least privilege at scale.
How you might answer: I’d give each service its own user-assigned managed identity, created with that service’s infrastructure code, holding only the data roles it needs on particular containers or vaults. I wouldn’t use one shared identity, because then a single compromise reaches everything. The role assignments sit in the same Bicep as the resources, so they get reviewed together.
9. What risks remain even with managed identities?
Why they ask this: They want you to see that “no secrets” isn’t “no risk”.
How you might answer: Anyone who can run code on the resource can use its identity, so a compromised VM or a bad deployment inherits those permissions, and that’s why over-broad roles are the real danger. I keep the roles narrow, watch the sign-in logs for those identities, and limit who can deploy to or log in to those resources.
Quick quiz
Q1. Which identity is deleted together with its resource?
- User-assigned managed identity
- System-assigned managed identity
- Service principal
- Guest user
Show answer
B — System-assigned identities live and die with one resource.
Q2. Which ID does a role assignment point to?
- Client ID
- Object (principal) ID
- Tenant ID
- Subscription ID
Show answer
B — Role assignments use the object ID.
Q3. What does AADSTS7000215 mean?
- No role assigned
- Invalid client secret
- Conditional Access block
- Wrong tenant
Show answer
B — The secret is wrong, expired, or the secret ID was used instead of the value.
Q4. A managed identity signs in but storage says it needs a data role. What is missing?
- A secret
- The identity
- A data role like Storage Blob Data Reader
- MFA
Show answer
C — The token is fine; RBAC is refusing the data action.
Q5. Why did the lab pass the container command with @file?
- It’s faster
- It avoids PowerShell and az.cmd quoting problems
- Containers need files
- It hides the command from Azure
Show answer
B — The CLI reads any argument starting with @ from a file, so quotes and && arrive intact.
Quick recap
Your code can now prove who it is without carrying a password around, and you can tell a sign-in failure apart from a permission failure.
- Managed identities give Azure resources an identity with no secret to store.
- A system-assigned identity goes with its resource, while a user-assigned one can be shared and stays.
- Client ID signs in; object ID gets the roles.
- AADSTS7000215 is a bad or expired secret; “required permissions” with a working sign-in is a missing role.
- Use managed identities inside Azure, and keep any remaining secrets owned and tracked.
Next lesson
Lesson 11: Azure virtual networks and subnets → You’ll plan an IP address range and build vnet-saat, which is the network you’ll use for the rest of the course.
Further reading: Azure managed identity
Want to go deeper into Azure managed identity? Microsoft’s overview is What are managed identities for Azure resources?, with guidance in Managed identity best practice recommendations. You can also see the full plan for this course on the Azure Cloud Administration course page.
