This chapter covers Key Vault References in Azure App Service and Azure Functions, a critical feature for securely managing secrets in application settings. For the AZ-204 exam, this topic falls under Domain 3 (Security), Objective 3.2: 'Manage secrets, certificates, and keys using Azure Key Vault.' Expect 5–10% of exam questions to touch on Key Vault References, often in scenarios involving secure configuration, managed identities, or secret rotation. Mastering this feature is essential for passing the security-focused questions and for building production-grade applications that follow the principle of least privilege.
Jump to a section
Imagine a large hotel with a central safe deposit vault. Each guest (App Service) needs to access sensitive items like credit card numbers or passport copies (secrets). Instead of carrying these items around, the guest receives a special token (a reference string) that they can present to the vault attendant. The attendant checks the token, verifies the guest's identity (managed identity), retrieves the actual item from a specific box, and hands it over. The guest never sees the vault key or the master lock combination—they only interact via the token. Importantly, the token does not contain the secret itself; it's just a pointer. If the hotel updates the contents of the safe deposit box (e.g., a new credit card number), the guest automatically gets the new item the next time they present the token, without needing a new token. This separation of concerns—the guest holds a reference, the vault holds the secret—is exactly how Key Vault References work in App Service. The reference string in the app setting is like the token; the managed identity is the guest's ID; Key Vault is the vault; and the secret is the sensitive data. The app never stores the secret in its configuration or memory permanently; it fetches it on demand from the vault.
1. What Are Key Vault References and Why Do They Exist?
Key Vault References are a feature in Azure App Service and Azure Functions that allow you to securely reference secrets stored in Azure Key Vault from your application settings. Instead of storing sensitive information like connection strings, API keys, or passwords directly in your app configuration (which could be exposed in source control, logs, or the Azure portal), you store the secret in Key Vault and reference it using a special syntax in your app settings. At runtime, App Service resolves the reference by fetching the secret from Key Vault using a managed identity assigned to the app.
This mechanism solves several problems: - Secret rotation: When a secret changes in Key Vault, the app automatically picks up the new value on the next request without redeployment. - Centralized management: Secrets are stored and managed in one place (Key Vault) with fine-grained access policies and auditing. - Reduced exposure: Secrets never appear in plaintext in app settings, logs, or configuration files. - Compliance: Helps meet security standards like PCI-DSS, HIPAA, and SOC 2 by avoiding hardcoded secrets.
2. How It Works Internally – The Mechanism
The process involves several components working together:
Step 1: Define the Reference You set an app setting with a value that follows the syntax:
@Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/)Or with a specific version:
@Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/abc123)You can also use a reference to a certificate:
@Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/certificates/mycert/)Step 2: Assign Managed Identity The App Service must have a system-assigned or user-assigned managed identity enabled. This identity is used to authenticate to Key Vault. To enable system-assigned managed identity via CLI:
az webapp identity assign --name <app-name> --resource-group <group>Step 3: Grant Access in Key Vault The managed identity's object ID must be granted at least 'Get' permission on secrets (and optionally 'List') in the Key Vault access policy. This can be done via CLI:
az keyvault set-policy --name <vault-name> --object-id <principal-id> --secret-permissions get listStep 4: Runtime Resolution
When the application starts or when a request is made, App Service's runtime encounters the reference string. It does the following:
1. Parses the @Microsoft.KeyVault(...) syntax.
2. Extracts the SecretUri.
3. Acquires a token for the managed identity (via the Azure Instance Metadata Service – IMDS endpoint http://169.254.169.254/metadata/identity/oauth2/token).
4. Calls Key Vault's REST API GET /secrets/{name}/{version} with the token.
5. Receives the secret value and caches it in memory (default cache duration is 24 hours, configurable via WEBSITE_KEY_VAULT_REFERENCE_CACHE_EXPIRATION).
6. Returns the secret value to the application code as if it were a plain app setting.
Important: If the secret is updated in Key Vault, the cached value will be used until the cache expires. To force a refresh, you can restart the app or wait for the cache to expire. The cache is per-instance, so in a scaled-out scenario, different instances may have different cached values until they all refresh.
3. Key Components, Values, Defaults, and Timers
Reference Syntax: @Microsoft.KeyVault(SecretUri=<uri>) – must be exact. The URI can be for a secret or certificate.
Secret URI Format: https://<vault-name>.vault.azure.net/secrets/<secret-name>/<version> – version is optional; if omitted, the latest version is used.
Managed Identity: System-assigned or user-assigned. User-assigned identity is specified via WEBSITE_USE_USER_ASSIGNED_IDENTITY app setting with the identity's client ID.
Cache Duration: Default 24 hours. Controlled by WEBSITE_KEY_VAULT_REFERENCE_CACHE_EXPIRATION app setting (value in seconds). Minimum is 3600 seconds (1 hour).
Permissions Required: At minimum Get permission on secrets. List is needed if you want to list secrets in the portal or use versionless references (though versionless works with Get only).
Supported App Types: Windows and Linux App Service, Azure Functions (both consumption and premium plans).
Limitations: Not supported in local development (use appsettings.Development.json with mock values). Not supported for connection strings in some older runtime stacks.
4. Configuration and Verification Commands
Enable system-assigned managed identity:
az webapp identity assign --name myapp --resource-group myrgOutput includes principalId.
Grant Key Vault access:
az keyvault set-policy --name myvault --object-id <principalId> --secret-permissions get listSet an app setting with a Key Vault reference:
az webapp config appsettings set --name myapp --resource-group myrg --settings "MySecret=@Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/)"Verify the reference is resolved: In the Azure portal, navigate to App Service > Configuration > Application settings. If the reference is valid, you will see a green checkmark and the resolved value (the secret) is shown as hidden. If there is an issue, you will see a red X and an error message.
Check logs for errors:
If the reference fails, check the application logs. Common errors include:
- Access denied due to missing permissions – managed identity lacks Get permission.
- Secret not found – incorrect secret name or version.
- Managed identity not configured – identity not enabled or misconfigured.
5. Interaction with Related Technologies
Managed Identities: The foundation for authentication. Without a managed identity, Key Vault References cannot work. The identity must have the correct RBAC role or access policy.
Azure Key Vault: Stores secrets, keys, and certificates. The vault must be in the same Azure Active Directory tenant as the App Service. Network restrictions (firewall, VNet) may block access; if the vault has a firewall, the App Service's outbound IPs must be allowed, or the app must be integrated into a VNet that can reach the vault.
App Service Slots: Key Vault References work in deployment slots. You can have different references per slot, pointing to different secrets (e.g., staging vs. production).
Azure Functions: Identical mechanism. References are set in the Function App's application settings.
Application Insights: If you enable logging, you may see Key Vault calls in the dependency tracking (if you use Application Insights SDK).
Local Development: Use appsettings.Development.json with placeholder values. The @Microsoft.KeyVault() syntax is only resolved in the Azure environment.
Create or Identify Secret in Key Vault
First, ensure the secret you want to reference exists in Azure Key Vault. You can create a secret via the Azure portal, CLI, or PowerShell. For example, using CLI: `az keyvault secret set --vault-name myvault --name mysecret --value "MySecretValue"`. Note the secret's URI, which will be used in the reference. If you plan to use versionless references, you must have 'List' permission on secrets. Otherwise, you can specify a specific version to avoid needing 'List' permission. The secret can be any string up to 25KB. For certificates, the reference retrieves the certificate's thumbprint and the certificate itself can be loaded via the `WEBSITE_LOAD_CERTIFICATES` setting.
Enable Managed Identity on App Service
The App Service or Function App must have a managed identity enabled. Use system-assigned for simplicity or user-assigned for more control. To enable system-assigned via CLI: `az webapp identity assign --name myapp --resource-group myrg`. This creates a service principal in Azure AD and assigns it to the app. The output includes the principalId (object ID) and tenantId. For user-assigned, first create the identity, then assign it to the app using `az webapp identity assign --name myapp --resource-group myrg --identities <identity-resource-id>`. Also set the app setting `WEBSITE_USE_USER_ASSIGNED_IDENTITY` to the client ID of the user-assigned identity.
Grant Key Vault Access to Managed Identity
The managed identity must have permission to read secrets from Key Vault. Use the Key Vault access policy (if using vault access model) or RBAC (if using Azure RBAC for Key Vault). For access policy, run: `az keyvault set-policy --name myvault --object-id <principalId> --secret-permissions get list`. The 'get' permission is mandatory; 'list' is needed only if you use versionless references or need to enumerate secrets. If using RBAC, assign the 'Key Vault Secrets User' role to the managed identity at the vault scope. Note that RBAC and access policies are mutually exclusive at the vault level; choose one model.
Configure App Setting with Key Vault Reference
Set an application setting with the reference syntax. In the Azure portal, go to App Service > Configuration > Application settings and add a new setting. The value must be exactly `@Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/)`. You can also use CLI: `az webapp config appsettings set --name myapp --resource-group myrg --settings "MySecret=@Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/)"`. The setting name can be anything; the value is the reference. Ensure there are no extra spaces. For slot-specific settings, use the `--slot` parameter.
Verify Reference Resolution and Test Application
After configuring, navigate to the App Service in the Azure portal. Under Configuration, the setting should show a green checkmark if the reference resolves successfully. If there is an error, a red X appears with an error message. Common errors: 'Access denied' (permissions missing), 'Secret not found' (wrong URI), or 'Managed identity not configured'. You can also browse to the app and check that it works. For debugging, enable application logging and look for Key Vault-related errors. The app code retrieves the secret as if it were a normal setting: `string mySecret = Environment.GetEnvironmentVariable("MySecret");` – the runtime resolves the reference before the code sees it.
Enterprise Scenario 1: E-commerce Platform with Rotating Database Credentials
A large e-commerce company runs a .NET Core web app on App Service that connects to an Azure SQL Database. To comply with PCI-DSS, database passwords must be rotated every 90 days. Previously, the team manually updated the connection string in the app settings and restarted the app, causing downtime. They switched to Key Vault References: they stored the SQL connection string (including password) as a secret in Key Vault, and set the app setting SqlConnectionString to a Key Vault reference. They enabled system-assigned managed identity and granted it 'Get' permission. Now, when the DBA rotates the password in Key Vault, the app automatically uses the new password after the cache expires (or they can restart the app to force refresh). This eliminated manual updates and reduced secret exposure. In production, they scaled to 10 instances; each instance caches the secret independently, but with a 24-hour cache, a rotation takes up to 24 hours to propagate. To mitigate, they set WEBSITE_KEY_VAULT_REFERENCE_CACHE_EXPIRATION to 3600 seconds (1 hour) for faster rotation. They also use deployment slots (staging/production) with different secrets for each slot, ensuring staging uses a non-production database.
Enterprise Scenario 2: Microservices with Shared Secrets
A financial services company uses Azure Functions for event-driven processing. Multiple functions need access to a shared API key for an external payment gateway. Instead of copying the key into each function's settings, they created a single secret in Key Vault and referenced it from all functions. Each function has its own managed identity (system-assigned) and a Key Vault access policy granting 'Get' permission. This centralizes management: when the payment provider rotates the key, they update only one secret. They also use user-assigned managed identities to simplify permission management across functions – a single user-assigned identity is assigned to all functions, and that identity is granted access to Key Vault. This reduced the number of access policy entries from dozens to one. They also integrated with Azure Policy to enforce that no function app settings contain plaintext secrets – any deviation triggers a compliance alert.
Common Misconfigurations
Missing Managed Identity: Forgetting to enable managed identity results in 'Access denied' errors because there is no identity to authenticate.
Wrong Secret URI: Using an incorrect vault name, secret name, or version. Always copy the URI from the Key Vault secret properties.
Network Restrictions: If the Key Vault has a firewall or VNet service endpoint, the App Service must be able to reach it. For VNet-integrated apps, ensure the vault allows trusted Microsoft services or has the correct VNet rules.
Cache Issues: After rotating a secret, the app continues to use the old cached value. Set a shorter cache expiration or restart the app to force refresh.
What AZ-204 Tests on Key Vault References
AZ-204 exam questions on this topic appear under Objective 3.2: 'Manage secrets, certificates, and keys using Azure Key Vault.' Specifically, you need to know:
The exact syntax of a Key Vault reference: @Microsoft.KeyVault(SecretUri=...).
The prerequisites: managed identity enabled and appropriate Key Vault permissions (Get, and optionally List).
How caching works: default 24-hour cache, configurable via WEBSITE_KEY_VAULT_REFERENCE_CACHE_EXPIRATION.
The difference between system-assigned and user-assigned managed identities.
How to handle secret rotation and cache invalidation.
The fact that references are resolved at runtime, not at deployment.
Common Wrong Answers and Why Candidates Choose Them
Wrong: 'Key Vault References require an access key for the vault.' – Candidates confuse Key Vault authentication with storage account access keys. Reality: Authentication is via managed identity, not keys.
Wrong: 'The secret value is stored in the app setting as plaintext after resolution.' – Some think the reference is a one-time substitution at deployment. Reality: The reference string remains in the setting; the runtime fetches the secret on each request (with caching).
Wrong: 'You must use the same vault for all references in an app.' – There is no such requirement; you can reference secrets from different vaults.
Wrong: 'Key Vault References work in local development.' – They do not; the syntax is only resolved in Azure. Local development must use mock values.
Specific Numbers, Values, and Terms Verbatim on the Exam
Reference syntax: @Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/).
Default cache duration: 24 hours.
Configurable via: WEBSITE_KEY_VAULT_REFERENCE_CACHE_EXPIRATION (value in seconds, minimum 3600).
Permissions: at least 'Get' on secrets; 'List' for versionless references.
Managed identity: system-assigned or user-assigned.
Supported in: App Service (Windows/Linux) and Azure Functions.
Edge Cases and Exceptions
Versionless references: If you omit the version, the runtime fetches the latest version. This requires 'List' permission. If you specify a version, only 'Get' is needed.
Certificates: You can reference a certificate; the runtime retrieves the certificate's thumbprint and loads it into the app's certificate store if WEBSITE_LOAD_CERTIFICATES is set.
Slot settings: You can mark a reference as a slot setting, so it stays with the slot during swaps. This is important for staging/production separation.
Key Vault firewall: If the vault has a firewall, the App Service's outbound IPs must be allowed, or the app must be VNet-integrated and the vault's firewall configured to allow that VNet.
How to Eliminate Wrong Answers Using the Underlying Mechanism
If an answer suggests that the secret is embedded in the app setting permanently, it is wrong because the reference is resolved dynamically.
If an answer mentions using a connection string with a username/password directly, that defeats the purpose – Key Vault References are the secure alternative.
If an answer says you need to redeploy after rotating a secret, that is false because caching handles eventual consistency (though you may need to restart to force immediate refresh).
Key Vault Reference syntax: @Microsoft.KeyVault(SecretUri=https://vaultname.vault.azure.net/secrets/secretname/).
Managed identity (system or user-assigned) must be enabled on the App Service.
Minimum Key Vault permission: Get on secrets; List needed for versionless references.
Default cache duration for resolved secrets is 24 hours; configurable via WEBSITE_KEY_VAULT_REFERENCE_CACHE_EXPIRATION (seconds, min 3600).
References are resolved at runtime, not at deployment or startup.
Not supported in local development; use mock values locally.
Supports both secrets and certificates (certificates require WEBSITE_LOAD_CERTIFICATES).
Works with deployment slots; can be marked as slot settings to keep references per slot.
If Key Vault has a firewall, ensure App Service outbound IPs are allowed or use VNet integration.
To force immediate refresh of a secret, restart the app or reduce cache expiration.
These come up on the exam all the time. Here's how to tell them apart.
Key Vault References
Secret stored in Key Vault, not in app config
Supports automatic rotation without redeployment
Requires managed identity and Key Vault permissions
Secret fetched at runtime with caching
Compliant with security standards (PCI-DSS, HIPAA)
Plain App Settings
Secret stored directly in app settings (plaintext)
Rotation requires manual update and redeployment
No additional setup needed
Secret is static until changed manually
Exposes secrets in portal, logs, and source control
Mistake
Key Vault References embed the secret value into the app setting permanently at deployment time.
Correct
The reference string remains in the app setting; the secret is fetched from Key Vault at runtime and cached in memory. The app setting never contains the actual secret value.
Mistake
You need to use the same Key Vault for all references in one App Service.
Correct
You can reference secrets from different Key Vaults in the same app. Each reference points to a specific vault and secret.
Mistake
Key Vault References work in local development using the same syntax.
Correct
The reference syntax is only resolved in the Azure App Service runtime. In local development, you must use mock values in appsettings.Development.json or similar.
Mistake
You must restart the app every time a secret changes in Key Vault.
Correct
The app automatically picks up the new secret after the cache expires (default 24 hours). You can force a refresh by restarting the app or setting a shorter cache duration.
Mistake
Key Vault References require the App Service to have a connection string to the vault.
Correct
Authentication is done via managed identity, not a connection string. The managed identity must have appropriate permissions on the Key Vault.
Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.
The syntax is `@Microsoft.KeyVault(SecretUri=<full-uri>)`. For example: `@Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/)`. The URI can include a version, e.g., `/secrets/mysecret/abc123`, or omit it to use the latest version. This string is set as the value of an application setting.
Not necessarily. The secret is cached for 24 hours by default. After the cache expires, the app automatically fetches the new value. To force an immediate refresh, you can restart the app or set the `WEBSITE_KEY_VAULT_REFERENCE_CACHE_EXPIRATION` app setting to a lower value (minimum 3600 seconds).
Yes, Azure Functions support Key Vault References exactly like App Service. You configure them in the Function App's application settings. The same prerequisites apply: managed identity enabled and Key Vault permissions granted.
At minimum, the `Get` permission on secrets is required. If you use versionless references (omit the version in the URI), you also need `List` permission. These are set via Key Vault access policies or Azure RBAC (Key Vault Secrets User role).
Common causes: (1) Managed identity not enabled on the app. (2) Managed identity lacks Get permission on the secret. (3) The secret URI is incorrect (wrong vault name, secret name, or version). (4) Key Vault firewall blocks the App Service. Check the error message for details and verify each component.
Yes, each app setting can point to a different Key Vault. There is no restriction on using multiple vaults. However, the managed identity must have appropriate permissions on each vault.
You can set different Key Vault References per slot by using slot-specific app settings. Mark the setting as a 'slot setting' so it stays with the slot during swaps. This allows staging and production to use different secrets (e.g., different database passwords).
You've just covered Key Vault References in App Service and Functions — now see how well it sticks with free AZ-204 practice questions. Full explanations included, no account needed.
Done with this chapter?