Azure Functions: Managed Identity

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

  1. Navigate to your Azure Function App in the Azure portal.
  2. In the left-hand navigation menu, under the "Settings" section, select Identity.
  3. Under the System assigned tab, set the Status to On.
  4. 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:

  1. Navigate to the Azure resource you want your Function App to access (e.g., your Azure Key Vault).
  2. In the left-hand navigation menu of that resource, select Access control (IAM).
  3. Click Add > Add role assignment.
  4. In the Role dropdown, select the role that grants the required permissions (e.g., Key Vault Secrets Officer).
  5. Under Assign access to, select Managed identity.
  6. Click Select members.
  7. Choose your Subscription.
  8. For Managed identity, select Function App.
  9. In the dropdown that appears, select your Function App.
  10. 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:


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: