Managed Identities
Earn 25 points (50 with Pro) in two steps
- ① Read through the lesson — each section gets a ✓ as you scroll through it.
- ② When every section has a ✓, tap Complete lesson.
0 of 10 read · keep scrolling
✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro
Lesson: Mastering Managed Identities for Azure Resources
Introduction to Managed Identities
In the early days of cloud computing, developers frequently faced a significant security dilemma: how to allow an application to talk to a database or a storage account without hardcoding credentials. The common, yet dangerous, solution was to store connection strings, API keys, or service principal secrets in configuration files, environment variables, or even directly in the source code. This practice, known as secret sprawl, created massive security risks. If a developer accidentally committed a configuration file to a public repository, an attacker could gain full access to the cloud environment within seconds.
Managed Identities for Azure resources were created to solve this fundamental problem. A Managed Identity provides an automatically managed identity in Microsoft Entra ID (formerly Azure Active Directory) for applications to use when connecting to resources that support Entra authentication. Instead of managing secrets, certificates, or tokens yourself, Azure handles the entire lifecycle of the identity. The application simply requests an access token from the local Azure platform, and Azure provides it, allowing the application to authenticate against services like Azure Key Vault, Azure SQL, or Azure Storage without ever touching a single credential.
Understanding Managed Identities is critical for any cloud professional because it shifts the burden of security from the developer to the platform. By adopting this approach, you minimize the risk of credential leakage, simplify the rotation of security tokens, and ensure that your applications follow the principle of least privilege. This lesson will guide you through the types of managed identities, how to implement them, and how to govern them effectively in a production environment.
Not read yet
Understanding the Two Types of Managed Identities
Before we dive into the implementation steps, it is essential to distinguish between the two types of Managed Identities available in Azure. Choosing the right one depends on your specific architecture and the lifecycle requirements of your application.
1. System-Assigned Managed Identity
A system-assigned identity is tied directly to a specific Azure resource, such as a Virtual Machine, an App Service, or a Function App. When you enable this identity on a resource, Azure creates a corresponding identity in Microsoft Entra ID. This identity is inextricably linked to the lifecycle of the resource. If you delete the resource, Azure automatically deletes the identity. This is the simplest option and is ideal for workloads where the identity is only needed for a single resource.
2. User-Assigned Managed Identity
A user-assigned identity is created as a standalone Azure resource. Because it exists independently, it can be assigned to multiple Azure resources simultaneously. For example, if you have a fleet of ten virtual machines that all need access to the same storage account, you can create one user-assigned identity and attach it to all ten machines. This makes it much easier to manage permissions across complex, multi-resource architectures. If you delete one of the virtual machines, the identity remains intact, as it is a separate resource.
Callout: System-Assigned vs. User-Assigned Think of a system-assigned identity like a temporary access badge tied to a specific employee’s laptop—if the laptop is destroyed, the badge is useless. A user-assigned identity is more like a corporate ID card that can be issued to multiple employees; if one employee leaves the company, the card still works for the others.
Not read yet
Implementation: How to Enable Managed Identities
Implementing Managed Identities is a straightforward process, but it involves two distinct phases: enabling the identity on the resource and assigning the necessary permissions (Role-Based Access Control) to that identity.
Enabling a System-Assigned Identity
Let us assume you have an Azure App Service that needs to read secrets from an Azure Key Vault.
- Navigate to your App Service in the Azure Portal.
- Select Identity from the left-hand navigation menu under the Settings section.
- On the System assigned tab, toggle the Status to On.
- Click Save.
At this point, Azure has registered an object ID for this App Service in your Entra ID tenant. However, the identity currently has no permissions. It exists, but it cannot do anything yet.
Enabling a User-Assigned Identity
If you prefer a user-assigned identity, the process is slightly different because you must create the identity resource first:
- Search for "Managed Identities" in the Azure portal and select Create.
- Provide a name, subscription, resource group, and region.
- Once created, go to your App Service (or Virtual Machine).
- Navigate to the Identity blade and select the User assigned tab.
- Click Add and select the Managed Identity you just created.
Not read yet
Assigning Permissions (RBAC)
Once the identity is enabled, it is time to grant it the authority to access other resources. This is done using Azure Role-Based Access Control (RBAC).
Tip: The Principle of Least Privilege Always assign the most restrictive role possible. If an application only needs to read data from a storage account, use the "Storage Blob Data Reader" role rather than "Storage Blob Data Contributor" or "Owner."
To assign a role to your Managed Identity:
- Navigate to the resource you want to access (e.g., the Azure Storage account).
- Select Access control (IAM) from the menu.
- Click Add and select Add role assignment.
- In the Role tab, select the appropriate role (e.g., Storage Blob Data Reader).
- In the Members tab, select Managed identity as the type of member.
- Click Select members, choose your subscription, and then select the identity you created (either system-assigned or user-assigned).
- Review and assign.
Not read yet
Authentication in Code: Using the Azure SDK
The true power of Managed Identities is realized when you integrate them into your application code. You no longer need to write logic to handle client IDs, client secrets, or token caching. Instead, you use the Azure Identity library, which is available for all major programming languages.
Example: Accessing Key Vault with C# (.NET)
When using the Azure SDK, the DefaultAzureCredential class is your best friend. It attempts to authenticate using multiple methods in a specific order, including Managed Identity, environment variables, and developer tools like the Azure CLI.
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
// The DefaultAzureCredential automatically detects the Managed Identity
// when running inside an Azure environment.
var client = new SecretClient(new Uri("https://your-vault-name.vault.azure.net/"), new DefaultAzureCredential());
// Accessing the secret
KeyVaultSecret secret = await client.GetSecretAsync("DatabasePassword");
Console.WriteLine($"The secret value is: {secret.Value}");
Why this is superior to traditional methods
In the code above, there is no mention of a password. If you run this code locally on your machine, DefaultAzureCredential will use your Azure CLI login credentials. When you deploy this code to an Azure App Service with a Managed Identity enabled, the exact same code detects the identity and retrieves the token automatically. This means your code remains environment-agnostic.
Not read yet
Comparison: Managed Identities vs. Other Methods
To understand why Managed Identities are the industry standard, it helps to compare them with older, less secure methods.
| Method | Security Level | Management Overhead | Rotation Required |
|---|---|---|---|
| Hardcoded Secrets | Extremely Low | High | Manual |
| Environment Variables | Low | Medium | Manual |
| Service Principals | Moderate | High | Yes (Secrets expire) |
| Managed Identities | Very High | Very Low | None (Automatic) |
Warning: Avoid Service Principal Secrets Many teams default to creating a Service Principal and generating a client secret. This is a common pitfall. Service principal secrets expire, which can cause production outages if someone forgets to update them in the code or key vault. Managed Identities eliminate this risk entirely because Azure manages the token issuance and rotation behind the scenes.
Best Practices for Managed Identities
Implementing Managed Identities is just the beginning. To maintain a secure environment, you should adhere to the following best practices:
1. Avoid Using System-Assigned Identities for Complex Workloads
While system-assigned identities are easy to set up, they become difficult to manage when you have a complex deployment pipeline (e.g., Infrastructure as Code). If you recreate your infrastructure from scratch, the system-assigned identity will have a new object ID, meaning you have to re-configure all your RBAC assignments. User-assigned identities are better for these scenarios because they persist even if the primary resource is deleted and recreated.
2. Audit Identity Usage
Use Azure Monitor and Microsoft Entra ID logs to audit which resources are accessing which services. Managed Identity sign-ins are logged in the Entra ID sign-in logs. You can create alerts if an identity attempts to access a resource it shouldn't, providing an early warning system for potential misconfigurations.
3. Use Infrastructure as Code (IaC)
Always define your Managed Identities and their RBAC assignments in your IaC templates (Bicep, ARM, or Terraform). This ensures that permissions are consistent across development, test, and production environments. Never manually configure permissions through the portal for production resources, as this leads to "configuration drift," where your environment becomes difficult to replicate or troubleshoot.
4. Limit the Scope of Permissions
Permissions should be assigned at the lowest possible level. Instead of assigning a role at the Resource Group level, assign it to the specific resource (e.g., the specific Key Vault or Storage Account). This ensures that even if an application is compromised, the blast radius is limited to that specific resource rather than everything in the resource group.
Not read yet
Common Pitfalls and Troubleshooting
Even with a straightforward implementation, developers often run into issues. Here are the most common problems and how to solve them.
Pitfall 1: Permissions Propagation Delay
When you assign an RBAC role to a Managed Identity, it is not always instantaneous. Azure's authorization system is globally distributed, and it can take a few minutes for the new permissions to propagate across all regions. If your application throws a "403 Forbidden" error immediately after you assign a role, wait 5 to 10 minutes and try again.
Pitfall 2: Confusing "Identity" with "Access"
A common mistake is assuming that enabling the Managed Identity is enough. Remember that the Identity is just the "passport." You still need to give the passport a "visa" (the RBAC role) to enter the resource. If your code is failing, check the Access control (IAM) settings on the target resource first to ensure the identity is listed there with the correct role.
Pitfall 3: Local Development vs. Production
Developers often struggle because their local code cannot authenticate using Managed Identity since it is not running in Azure. This is where DefaultAzureCredential is essential. Ensure your local environment is configured with the Azure CLI or PowerShell, and that your developer account has the same RBAC permissions that the Managed Identity will have in production.
Callout: Troubleshooting Checklist
- Is the Managed Identity enabled on the source resource?
- Is the Managed Identity granted the correct RBAC role on the target resource?
- Has enough time passed for the RBAC role assignment to propagate?
- Are you using the latest version of the Azure SDK? (Older versions may not support Managed Identity correctly).
- Does the target resource (e.g., Key Vault) have a firewall that blocks your specific network?
Not read yet
Advanced Scenario: Managed Identities with Key Vault Access Policies
While RBAC is the modern way to manage access, some older Azure resources still use "Access Policies" (notably Azure Key Vault). If you are using an older Key Vault configuration, you must add the Managed Identity to the Access Policy list.
- Go to your Key Vault.
- Select Access policies.
- Click Create or Add.
- Select the permissions (e.g., Get, List).
- In the Principal section, search for the name of your Managed Identity.
- Save the policy.
Note: Microsoft is moving away from Access Policies in favor of RBAC for Key Vault. If you are starting a new project, always choose the "Azure role-based access control" permission model when creating your Key Vault.
Integrating Managed Identities with Azure SQL
Connecting to an Azure SQL database is a classic use case for Managed Identities. Instead of using a username and password in your connection string, you can use the identity to authenticate.
Steps to configure:
- Enable a Managed Identity on your App Service.
- Connect to your SQL database using an account that has "Active Directory Admin" privileges (or use SQL authentication to log in initially).
- Execute the following SQL command to create a user for your identity:
CREATE USER [Your-Managed-Identity-Name] FROM EXTERNAL PROVIDER; ALTER ROLE db_datareader ADD MEMBER [Your-Managed-Identity-Name]; ALTER ROLE db_datawriter ADD MEMBER [Your-Managed-Identity-Name]; - Update your connection string in your application to remove the User ID and Password, and replace it with
Authentication=Active Directory Managed Identity;.
This approach is significantly more secure than storing SQL credentials. Even if someone steals your connection string, it will be useless to them because the connection string is bound to the identity of the server running the application.
Not read yet
Governance and Compliance
In a large enterprise, you cannot manually track every identity. You should implement governance policies to ensure that all resources follow the standard of using Managed Identities.
Azure Policy
You can use Azure Policy to prevent the creation of resources that do not use Managed Identities or to audit existing resources. For example, you can create a policy that denies the deployment of any App Service that does not have a Managed Identity enabled. This forces development teams to follow security standards from the very first day of development.
Monitoring via Log Analytics
You can stream your Entra ID sign-in logs to a Log Analytics workspace. By running Kusto Query Language (KQL) queries, you can identify which identities are being used most frequently and spot any anomalies.
Example KQL query to find sign-ins by Managed Identities:
SigninLogs
| where IdentityType == "ManagedIdentity"
| project TimeGenerated, AppDisplayName, UserPrincipalName, ResultType
| order by TimeGenerated desc
Not read yet
Summary of Key Takeaways
Managed Identities are the cornerstone of modern, secure Azure development. By moving away from static credentials, you build more resilient, easier-to-maintain, and significantly more secure applications. Here are the core concepts to remember:
- Elimination of Secrets: Managed Identities remove the need to store and rotate credentials (passwords, certificates, tokens) in your application code or configuration, effectively ending secret sprawl.
- Identity Types: Use System-Assigned identities for simple, single-resource workloads where the identity lifecycle should match the resource. Use User-Assigned identities for complex, multi-resource architectures where the identity needs to be reused across different services.
- Authentication via SDK: Always use the
DefaultAzureCredentialclass from the Azure SDK. This allows your code to run seamlessly across local development environments and various Azure production resources without modification. - RBAC is Mandatory: Enabling the identity is only the first step. You must grant the identity the minimum necessary permissions on the target resource using Azure RBAC. Always follow the principle of least privilege.
- Governance through Policy: Use Azure Policy to enforce the use of Managed Identities across your organization. This prevents developers from falling back to insecure legacy practices like hardcoding secrets.
- Patience with Propagation: Remember that RBAC assignments take time to propagate across the Azure fabric. If you face an authentication error immediately after setup, wait a few minutes before troubleshooting.
- Future-Proofing: Always prefer RBAC-based access over legacy Access Policies, especially in services like Azure Key Vault and Azure SQL, to ensure compatibility with evolving cloud security standards.
By internalizing these concepts and applying them to your daily work, you will significantly improve the security posture of your cloud infrastructure. You are no longer managing secrets; you are managing identities and policies, which is a much more scalable and secure way to operate in the cloud.
Not read yet
Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.
- Introduction to Microsoft Entra ID
- Introduction to Microsoft Entra ID Quiz5q
- Configure Tenant Settings
- Configure Tenant Settings Quiz5q
- Custom Domain Names
- Custom Domain Names Quiz5q
- Device Identity and Registration
- Device Identity and Registration Quiz5q
- Company Branding Configuration
- Company Branding Configuration Quiz5q
- Create and Manage User Accounts
- Create and Manage User Accounts Quiz5q
- Bulk User Operations
- Bulk User Operations Quiz5q
- Create and Manage Groups
- Create and Manage Groups Quiz5q
- Dynamic Group Membership
- Dynamic Group Membership Quiz5q
- Administrative Units
- Administrative Units Quiz5q
- License Assignment and Management
- License Assignment and Management Quiz5q
- External Collaboration Settings
- External Collaboration Settings Quiz5q
- Invite External Users
- Invite External Users Quiz5q
- B2B Collaboration and Direct Connect
- B2B Collaboration and Direct Connect Quiz5q
- Cross-Tenant Access Settings
- Cross-Tenant Access Settings Quiz5q
- Identity Provider Configuration
- Identity Provider Configuration Quiz5q
- Microsoft Entra Connect Overview
- Microsoft Entra Connect Overview Quiz5q
- Password Hash Synchronization
- Password Hash Synchronization Quiz5q
- Pass-Through Authentication
- Pass-Through Authentication Quiz5q
- Federation with AD FS
- Federation with AD FS Quiz5q
- Entra Connect Cloud Sync
- Entra Connect Cloud Sync Quiz5q
- Authentication Methods Overview
- Authentication Methods Overview Quiz5q
- Passwordless Authentication
- Passwordless Authentication Quiz5q
- Self-Service Password Reset
- Self-Service Password Reset Quiz5q
- Password Protection and Smart Lockout
- Password Protection and Smart Lockout Quiz5q
- FIDO2 Security Keys
- FIDO2 Security Keys Quiz5q
- Microsoft Authenticator App
- Microsoft Authenticator App Quiz5q
- Conditional Access Overview
- Conditional Access Overview Quiz5q
- Create Conditional Access Policies
- Create Conditional Access Policies Quiz5q
- Named Locations and Terms of Use
- Named Locations and Terms of Use Quiz5q
- Session Controls and App Controls
- Session Controls and App Controls Quiz5q
- Authentication Strength Policies
- Authentication Strength Policies Quiz5q
Spend your points to unlock exam-style practice questions
Spend points to unlock SC-300 exam-style practice questions.
Practice for SC-300