Build Secretless Azure App Service Deployments with Managed Identities and Key Vault

Tim Rabbetts | November 25, 2026

Secrets are rarely exposed because a developer deliberately publishes them. More often, a database password is added to a local configuration file, copied into a deployment variable, printed by a failed build, or committed temporarily while debugging. Months later, nobody is quite sure where the credential exists or who can still use it.

Azure App Service gives you a better default. The application can authenticate to Azure using a managed identity issued by Microsoft Entra ID, while secrets that still need to exist can be stored in Azure Key Vault. The application or App Service platform then retrieves what it needs without a client secret, certificate or password being embedded in source control.

This is not the same as making an application magically secret-free. If a third-party API only supports an API key, that key still exists somewhere. The improvement is that it is held in a controlled store, access is granted to a specific workload identity, and retrieval can be audited and rotated independently of the codebase.

The architecture and the important distinction

A useful design separates four responsibilities:

  • Authentication: the App Service proves its identity to Azure using a system-assigned or user-assigned managed identity.
  • Authorisation: Azure RBAC determines which resources that identity can access.
  • Secret storage: Key Vault stores passwords, API keys, certificates or other sensitive values.
  • Application configuration: App Service settings expose non-secret configuration and, where suitable, Key Vault references to the application.

Managed identity handles authentication, not authorisation. Enabling an identity does not give an App Service permission to read a vault, storage account or database. You must still grant the identity the narrowest role that satisfies the workload.

Microsoft’s App Service documentation describes managed identities as identities whose lifecycle is managed by Azure, removing the need for your team to provision and rotate credentials used by the application to authenticate to supported Azure services. See the App Service managed identity documentation and the secure App Service connectivity guide.

Choose the identity type deliberately

System-assigned identity

A system-assigned identity belongs to one Azure resource. When you enable it on an App Service, Azure creates the identity and ties its lifecycle to that app. Deleting the app also removes the identity.

This is usually the simplest option for a single application and environment. It avoids an extra identity resource and makes ownership clear: the production app has a production identity, and the staging app has another one.

The main limitation is lifecycle coupling. Recreating the App Service creates a new identity. Any role assignments granted to the old identity must be recreated, and automation must account for the identity becoming available before it attempts to assign permissions or configure Key Vault references.

User-assigned identity

A user-assigned identity is a separate Azure resource that can be attached to one or more workloads. Its lifecycle is independent of the App Service. This makes it useful when several equivalent applications need the same permissions, or when an identity must exist before an application is created.

That flexibility also increases the blast radius. If the same identity is attached to development, staging and production, a compromise of one workload may provide access intended for all three. Microsoft’s managed identity recommendations explicitly emphasise least privilege and careful choice between system-assigned and user-assigned identities.

For most independent applications, start with one system-assigned identity per App Service per environment. Use a user-assigned identity when you have a concrete lifecycle or reuse requirement, not merely because it appears more reusable.

Prerequisites and naming assumptions

The examples below assume that you already have an Azure subscription, an existing App Service app and permission to create role assignments. You also need Azure CLI access through Azure Cloud Shell or a local installation.

Set variables for the resource group, application, region and vault. Key Vault names are globally unique, so choose a name that is not already in use.

az login

resourceGroup="rg-orders-production"
appName="orders-web-production"
vaultName="kv-orders-production"
location="uksouth"

az account show

Do not place real secret values in shell history if your workstation or shared build runner retains command history. For a production pipeline, use a protected pipeline variable, an interactive prompt, or a separate provisioning process with appropriate secret handling.

Create a Key Vault using Azure RBAC

Azure Key Vault supports different permission models. For a new implementation, Azure RBAC is generally the clearer choice because access is managed through standard role assignments and can be integrated with broader Azure governance. Microsoft’s Key Vault RBAC guidance recommends assigning roles at the vault scope in common application-per-environment designs and avoiding unnecessarily broad permissions.

az keyvault create \
  --resource-group "$resourceGroup" \
  --name "$vaultName" \
  --location "$location" \
  --enable-rbac-authorization true

Store an initial secret. The value shown here is deliberately a placeholder; replace it through a secure provisioning mechanism rather than committing it to a script.

read -rsp "Enter the upstream API key: " upstreamApiKey
printf '\n'

az keyvault secret set \
  --vault-name "$vaultName" \
  --name "upstream-api-key" \
  --value "$upstreamApiKey"

unset upstreamApiKey

Secret names may contain letters, numbers and hyphens, which makes names such as upstream-api-key convenient for App Service settings. Avoid putting the secret value, or a value derived from it, into resource names, tags or diagnostic messages.

Enable the App Service managed identity

Enable a system-assigned identity on the web app and capture its principal ID. The principal ID identifies the identity in Microsoft Entra ID and is the value used when granting the vault role.

principalId=$(
  az webapp identity assign \
    --resource-group "$resourceGroup" \
    --name "$appName" \
    --query principalId \
    --output tsv
)

echo "$principalId"

There can be a short delay between creating the identity and being able to use it in a role assignment. If the next command reports that the principal cannot be found, wait briefly and retry rather than creating a second identity or weakening the permissions model.

Now grant the application the Key Vault Secrets User role on this vault. This role allows the identity to read secret values but does not grant it permission to manage the vault or change secrets.

vaultId=$(
  az keyvault show \
    --resource-group "$resourceGroup" \
    --name "$vaultName" \
    --query id \
    --output tsv
)

az role assignment create \
  --assignee-object-id "$principalId" \
  --assignee-principal-type ServicePrincipal \
  --role "Key Vault Secrets User" \
  --scope "$vaultId"

Keep the identity that deploys infrastructure separate from the identity used by the running application. A release pipeline may need permission to create or update secrets, while the web app normally needs only to read them. Giving the application a role such as Key Vault Secrets Officer simply because deployment automation needs it is an avoidable privilege escalation.

Expose a secret with a Key Vault reference

App Service can resolve a Key Vault reference as an app setting. Your application reads the setting in the same way it would read an ordinary environment variable, but the value is maintained in Key Vault rather than stored directly in the App Service configuration.

The reference can use a vault and secret name:

keyVaultReference="@Microsoft.KeyVault(VaultName=${vaultName};SecretName=upstream-api-key)"

az webapp config appsettings set \
  --resource-group "$resourceGroup" \
  --name "$appName" \
  --settings "UPSTREAM_API_KEY=$keyVaultReference"

Alternatively, use a secret URI. Omitting the version tells App Service to resolve the latest version. Including a version gives you deterministic configuration, which can be helpful during a controlled rollback but means that rotation will not automatically move the application to the new version.

Application code should not know whether UPSTREAM_API_KEY comes from Key Vault, a local environment file or an App Service setting. That abstraction keeps local development practical while making production configuration safer.

When to read through App Service and when to use the SDK

Key Vault references are a good fit when an existing application already consumes environment variables or connection strings. They generally require no application code change. The platform resolves the reference and supplies the result to the process as configuration.

Use the Azure SDK directly when the application needs to fetch several secrets dynamically, select a particular version, react to rotation without a restart, or use Key Vault keys and certificates rather than simply injecting a configuration value. In that design, the application authenticates with DefaultAzureCredential locally and with managed identity when deployed to Azure.

The following JavaScript example uses one credential instance and one Key Vault client. Reusing the credential and client avoids constructing new authentication objects for every request.

import { DefaultAzureCredential } from "@azure/identity";
import { SecretClient } from "@azure/keyvault-secrets";

const vaultName = process.env.KEY_VAULT_NAME;

if (!vaultName) {
  throw new Error("KEY_VAULT_NAME is required");
}

const credential = new DefaultAzureCredential();
const client = new SecretClient(
  `https://${vaultName}.vault.azure.net`,
  credential
);

export async function getUpstreamApiKey() {
  const result = await client.getSecret("upstream-api-key");

  if (!result.value) {
    throw new Error("The upstream API key is empty or unavailable");
  }

  return result.value;
}

Install the relevant packages with your normal package manager:

npm install @azure/identity @azure/keyvault-secrets

Microsoft’s JavaScript authentication guidance recommends credential reuse and documents how the Azure Identity library selects credentials in local and hosted environments. Do not log the returned value, include it in an exception, or attach it to request telemetry.

Secret rotation is a process, not a setting

Key Vault supports versioned secrets. Setting a secret with the same name creates a new version rather than overwriting the old value in place. That gives you a safer rotation model: create the replacement, test it, move consumers to it, and retain the previous version long enough to recover if needed.

For an unversioned App Service Key Vault reference, App Service caches the resolved value and checks for a newer version periodically. Microsoft documents a refresh interval of up to 24 hours. Changing the App Service configuration causes a restart and an immediate refetch; Microsoft also documents an authenticated refresh endpoint when an explicit refresh is required. Read the current details in the Key Vault references documentation before building an operational runbook around the behaviour.

That caching has two practical consequences:

  • Do not rotate a credential at the upstream service and immediately assume every App Service instance has the new value.
  • For urgent rotation, plan an explicit refresh or controlled restart, then verify the application’s health and downstream authentication.

Some APIs accept two active keys specifically to support overlap. Where possible, create the new key, deploy or refresh consumers, verify successful traffic, and revoke the old key only after the transition window has passed. If the external service supports only one active key, schedule the change and provide a rollback procedure.

Keep deployment slots and environments isolated

Development, staging and production should not share a vault simply because sharing one is convenient. Separate vaults reduce accidental cross-environment access and make it easier to reason about which workload can read which secret.

App Service deployment slots add another concern: some settings should move with the code and others should remain attached to the slot. A production database reference must not swap into staging during a deployment, and a staging API key must not follow code into production.

Mark environment-specific Key Vault references as deployment slot settings. With Azure CLI, use the slot-specific option when configuring the setting:

slotName="staging"
stagingVaultName="kv-orders-staging"
stagingReference="@Microsoft.KeyVault(VaultName=${stagingVaultName};SecretName=upstream-api-key)"

az webapp config appsettings set \
  --resource-group "$resourceGroup" \
  --name "$appName" \
  --slot "$slotName" \
  --settings "UPSTREAM_API_KEY=$stagingReference" \
  --slot-settings "UPSTREAM_API_KEY"

The App Service deployment slot documentation explains how slot settings remain associated with the slot during a swap. Treat this as part of release design, not as a last-minute portal checkbox.

Network restrictions can look like permission failures

A correct RBAC assignment does not guarantee network connectivity. If the vault uses firewall rules, private endpoints or restricted public access, the App Service must also have a permitted network path. A request can therefore fail because the identity lacks a role, because DNS resolves incorrectly, or because the application cannot reach the vault endpoint.

When troubleshooting a restricted vault, check these separately:

  1. Does the App Service have the expected managed identity?
  2. Does that identity have the required data-plane role on the correct vault?
  3. Can the App Service network reach the vault?
  4. Is the Key Vault reference using the intended vault and secret name?
  5. Has the setting been marked correctly for the current deployment slot?

Do not respond to a network failure by granting the application a broader role. Authentication, authorisation and network access are independent controls.

Monitoring, auditing and safe diagnostics

Key Vault access should be observable. Microsoft documents audit events for authenticated requests, failed requests and operations involving secrets, keys and certificates. Send the vault’s diagnostic logs to an appropriate Log Analytics workspace or other protected destination, and restrict access to those logs because request metadata can still be sensitive.

The Key Vault logging documentation describes operations such as secret reads and the identity presented with the request. Use this information to answer practical questions: did the production app read the secret after deployment, did an unexpected principal request it, and are repeated failures indicating a broken role assignment or network route?

Application logs should report that a dependency could not be authenticated, not the secret itself. A useful error can include the dependency name, correlation ID and operation type while omitting the token, API key, connection string and full secret URI where it could reveal unnecessary detail.

Performance and resilience considerations

Fetching a secret from Key Vault on every incoming HTTP request adds network latency and introduces an avoidable dependency in the request path. Load configuration once at startup, cache it in memory for a controlled period, or use App Service Key Vault references when the application’s configuration model allows it.

Caching should not become an excuse to keep stale credentials indefinitely. Choose a refresh policy that matches the rotation process. For frequently rotated credentials, use a background refresh or SDK-based design with clear failure handling. For stable configuration, startup loading through a Key Vault reference may be simpler and more predictable.

Do not make the entire application unavailable merely because an optional feature’s secret cannot be read. Classify dependencies: a payment gateway credential may be essential for checkout, while an analytics key may be optional. Fail safely, avoid retry storms and use bounded retries with back-off for transient Azure errors.

A practical review checklist

  • Each environment has its own vault and workload identity unless sharing is explicitly justified.
  • The running application has only the data-plane permissions it needs.
  • Infrastructure automation and application runtime identities are separate.
  • Secrets are not present in source control, Docker images, build output or ordinary deployment logs.
  • Key Vault references are marked as slot settings where environment-specific values must not swap.
  • Rotation has an overlap, validation and rollback procedure.
  • Vault network restrictions have been tested from the actual App Service environment.
  • Key Vault audit logs are enabled and reviewed.
  • Application code does not print secret values or include them in telemetry.
  • Secret retrieval is not performed synchronously for every request.

The most valuable change is usually not a new SDK call. It is removing the assumption that an application must carry a reusable credential in order to authenticate. Let Azure issue the workload identity, let RBAC define its reach, keep unavoidable secrets in Key Vault, and make rotation and auditing part of the deployment lifecycle. That approach reduces the number of places a secret can leak without pretending that secret management is no longer an operational responsibility.