Creating and Using a Managed Identity for Your Azure Functions
Managed identities for Azure resources allow your Azure Functions to authenticate to services that support Azure AD authentication (like Azure Key Vault, Azure Storage, and Azure SQL Database) without needing to manage credentials in your code.
There are two types of managed identities: System-assigned and User-assigned. This guide will focus on creating a System-assigned managed identity, which is tied directly to the lifecycle of your Azure Function App.
Step 1: Enable Managed Identity in Azure Portal
- Navigate to your Azure Function App in the Azure portal.
- In the left-hand navigation menu, under the "Settings" section, select Identity.
- Under the System assigned tab, set the Status to On.
- Click Save.
When you enable the system-assigned managed identity, Azure creates an identity for your Function App in Azure Active Directory. The Principal ID (Object ID) of this identity is displayed on this page.
Keep a note of the Principal ID. You'll need it later to grant permissions to other Azure services.
Step 2: Grant Permissions to Other Azure Services
Once the managed identity is created, you need to grant it the necessary permissions to access other Azure resources. For example, to access secrets in Azure Key Vault:
- Navigate to the Azure resource you want your Function App to access (e.g., your Azure Key Vault).
- In the left-hand navigation menu of that resource, select Access control (IAM).
- Click Add > Add role assignment.
- In the Role dropdown, select the role that grants the required permissions (e.g., Key Vault Secrets Officer).
- Under Assign access to, select Managed identity.
- Click Select members.
- Choose your Subscription.
- For Managed identity, select Function App.
- In the dropdown that appears, select your Function App.
- Click Save.
Step 3: Use the Managed Identity in Your Function Code
Your Azure Function can now authenticate to services using its managed identity. This typically involves using the Azure SDKs, which automatically detect and use the managed identity when running in Azure.
Example: Accessing Azure Key Vault using C#
Ensure you have the appropriate NuGet packages installed:
Azure.IdentityAzure.Security.KeyVault.Secrets(or relevant Key Vault package)
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
public class KeyVaultExampleFunction
{
[Function("KeyVaultExample")]
public async Task Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req,
FunctionContext context)
{
var logger = context.GetLogger();
logger.LogInformation("C# HTTP trigger function processed a request.");
// Replace with your Key Vault URI
string keyVaultUri = "https://your-key-vault-name.vault.azure.net/";
string secretName = "YourSecretName";
try
{
// DefaultAzureCredential will automatically pick up the Managed Identity
var client = new SecretClient(new Uri(keyVaultUri), new DefaultAzureCredential());
KeyVaultSecret secret = await client.GetSecretAsync(secretName);
logger.LogInformation($"Successfully retrieved secret '{secretName}'. Value: {secret.Value}");
// In a real scenario, you would return the secret value or use it
// For demonstration, we'll just log it.
// Consider security implications of returning secrets directly in HTTP responses.
}
catch (Exception ex)
{
logger.LogError($"Error accessing Key Vault: {ex.Message}");
// Handle exception appropriately
}
}
}
The DefaultAzureCredential class from Azure.Identity is the recommended way to handle authentication. It intelligently tries multiple credential sources, including the managed identity, environment variables, and other methods, making your code portable.
Important Considerations:
- Principal ID: The Principal ID (Object ID) of the managed identity is crucial for assigning roles.
- Role Assignments: Ensure you assign the *least privilege* necessary. Grant only the permissions your function absolutely needs.
- Key Vault URIs: When using Key Vault, ensure your Function App has network access to the Key Vault. This might involve configuring VNet integration or firewall rules.
- User-Assigned Identities: For more complex scenarios or when you need an identity independent of a single Function App's lifecycle, consider User-assigned managed identities.