Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 57 ยท Security, Monitoring and Cost

Key Vault

Learn Azure Key Vault: secrets, keys and certificates, RBAC vs access policies, soft delete, purge protection, App Service references and rotation, with stand-ins.

Every application has secrets: database passwords, API keys, signing keys, TLS certificates. The worst place for them is source code or a settings file in a repository, because they spread to every laptop, build log and backup. Azure Key Vault is a managed service whose only job is to store these values safely, control who can read them, record every access, and help you rotate them.

This lesson explains the three kinds of objects a vault holds, how access is controlled, the protections against accidental deletion, how App Service reads secrets without code changes, and how rotation works. Commands are read-only (they need a subscription). The runnable examples are stand-ins: an envelope encryption program that uses Node's real node:crypto to show how a vault's keys protect data, and a small model of secret versions, soft delete and purge protection.

Secrets, keys and certificates

A vault stores three kinds of objects:

Object What it is Typical use
Secret Any small value up to 25 KB, stored as text Passwords, connection strings, API tokens
Key A cryptographic key, created or imported; software-protected or HSM-protected Signing, encrypting, wrapping other keys
Certificate A certificate plus its private key, with lifecycle management (renewal, issuer integration) TLS certificates

The important difference is between secrets and keys. If you store a password as a secret, you can read the value back. A key is different: for an HSM-protected key you can ask the vault to sign or encrypt for you, but the private key material never leaves the vault. Your code sends data to the vault and receives a result.

Each object has versions. Setting a secret again does not overwrite it; it adds a new version, and a reader who asks for the secret without a version gets the latest one.

Vaults come in tiers: Standard (software-protected keys) and Premium (HSM-protected keys). There is also Managed HSM for dedicated, single-tenant hardware modules. A vault is regional, and the name becomes part of its URL: https://myvault.vault.azure.net.

Terminal
# Create a vault with RBAC authorization, soft delete and purge protection (read-only)
az keyvault create \
  --resource-group rg-demo --name kv-demo-4821 --location westeurope \
  --enable-rbac-authorization true --enable-purge-protection true

az keyvault secret set --vault-name kv-demo-4821 --name db-password --value "s3cret!"
az keyvault secret show --vault-name kv-demo-4821 --name db-password --query value -o tsv
az keyvault secret list-versions --vault-name kv-demo-4821 --name db-password -o table

Vault names are globally unique, 3 to 24 characters. Use --query value carefully: it prints the secret to your terminal.

Controlling access: RBAC or access policies

Key Vault has two permission models:

  • Azure RBAC (recommended). You assign roles such as Key Vault Secrets User (read secret values), Key Vault Secrets Officer (manage secrets), Key Vault Crypto User (use keys) or Key Vault Administrator at the vault, or at the level of a single secret. This is the same model as the rest of Azure (see Role-Based Access Control), it works with governance tools and logs, and it supports least privilege per object.
  • Vault access policies (the older model). Each policy lists an identity and a set of permissions on all secrets, keys or certificates in the vault. It is all-or-nothing within a category, with no per-object control.

You pick one per vault with --enable-rbac-authorization. New vaults should use RBAC.

There are two separate planes. The management plane (create or delete a vault, change settings, assign roles) is controlled by RBAC roles such as Contributor. The data plane (read a secret) needs a data-plane role. This surprises many people: Owner or Contributor on the vault does not let you read its secrets, which is intentional. Someone who manages infrastructure should not automatically see passwords.

Who should get the data-plane role? Applications should use a managed identity (see Managed Identities and Service Principals), never a stored client secret. A client secret to reach the vault would only move the "secret in code" problem one step.

Terminal
az role assignment create \
  --assignee-object-id <managed-identity-principal-id> \
  --assignee-principal-type ServicePrincipal \
  --role "Key Vault Secrets User" \
  --scope $(az keyvault show -n kv-demo-4821 --query id -o tsv)

Also restrict the network: turn on the vault firewall or a private endpoint (see Private Endpoints, VPN and ExpressRoute) so the vault is not open to the whole internet.

Reading a secret from code

With a managed identity, the application has no credential to protect. This is the shape of the code, shown read-only (it needs the real SDK and an identity):

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

const client = new SecretClient(
  "https://kv-demo-4821.vault.azure.net",
  new DefaultAzureCredential()
);

const secret = await client.getSecret("db-password");
console.log(secret.properties.version); // the value is in secret.value

Cache the value in memory for a short time instead of calling the vault for every request; vaults have request limits, and each call adds latency.

App Service and Functions: Key Vault references

For App Service and Azure Functions you often do not need any SDK. An app setting can contain a Key Vault reference, and the platform resolves it using the app's managed identity before your code starts:

TEXT
DB_PASSWORD = @Microsoft.KeyVault(SecretUri=https://kv-demo-4821.vault.azure.net/secrets/db-password/)

Your code reads process.env.DB_PASSWORD (see App Service and Web Apps) as if it were a normal setting. If you leave the version out of the URI, the platform picks up new versions automatically (it checks periodically, so a change may take some time to appear). A reference that fails shows an error status in the portal, usually because the identity lacks the role or a firewall blocks access.

Soft delete and purge protection

Deleting a secret by mistake, or a malicious delete, could be catastrophic. Key Vault has two layers of defense:

  • Soft delete (always on for new vaults). A deleted vault or object goes into a "deleted" state for a retention period of 7 to 90 days (the default is 90). During that time you can recover it.
  • Purge protection (optional, but strongly recommended for production). While it is on, nobody, not even an Owner, can permanently purge a deleted object before the retention period ends. Once enabled it cannot be turned off.

Without purge protection, soft-deleted objects can be purged early, which defeats part of the safety net. With it, a vault name stays reserved while deleted objects wait, so you cannot reuse the name immediately.

The second stand-in models versions, soft delete and purge protection. It is not Key Vault; it only demonstrates the rules.

JS Secret versions, soft delete and purge protection

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Change purgeProtection to false and run it again: the purge on day 41 now succeeds, and the recover step has nothing left to recover. That is exactly the situation purge protection prevents.

Keys and envelope encryption

Why does a vault offer keys at all? Because encrypting large data directly with a vault key would be slow and expensive: every byte would travel to the vault. The standard solution is envelope encryption:

  1. Generate a random data encryption key (DEK) locally for each record or file.
  2. Encrypt the data with the DEK (fast, local).
  3. Ask the vault to wrap (encrypt) the DEK with a key encryption key (KEK) that never leaves the vault.
  4. Store the wrapped DEK next to the ciphertext. Discard the plain DEK.

To read the data you send the wrapped DEK to the vault, which unwraps it if you are authorized, and then decrypt locally.

sequenceDiagram
    participant App as Application
    participant KV as Key Vault (KEK)
    App->>App: generate random DEK
    App->>App: encrypt data with DEK
    App->>KV: wrap DEK
    KV-->>App: wrapped DEK
    App->>App: store ciphertext + wrapped DEK
    Note over App,KV: To read: send wrapped DEK to the vault, receive the DEK, decrypt locally

Only small keys travel to the vault; the bulk data stays local.

Azure Storage, Azure SQL (transparent data encryption with customer-managed keys) and disk encryption all use this pattern. The stand-in below uses Node's real AES-256-GCM from node:crypto to build a miniature vault. Its MiniVault class keeps keys in a private field and exposes only wrap and unwrap, like the real service does. The real service uses its own wrap algorithms (for example RSA-OAEP or AES key wrap), so this is an illustration of the idea. It then rotates the key: only the small wrapped DEK is re-wrapped, and the bulk data is untouched.

Node.js Envelope encryption and key rotation with node:crypto

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The wrapped DEK is 60 bytes (12 for the IV, 16 for the tag and 32 for the key), however big the data is. That is why rotation is cheap: a vault with a million records re-wraps a million small keys, and never re-encrypts terabytes.

Rotation

Secrets and keys should not live forever. Rotation limits the damage of a leak and is required by many compliance rules.

  • Keys support an automatic rotation policy (for example, new version every 90 days, with a notification before expiry). Applications that always ask for "the latest" version, or that use envelope encryption, rotate without a code change.
  • Secrets are harder because the secret must also change in the system that checks it (a database password, a third-party API). The usual approach is a function or automation triggered by the Event Grid SecretNearExpiry event that creates the new credential, updates the target, and stores a new secret version (see Event Grid and Event Hubs).
  • Two-credential rotation avoids downtime: keep two valid credentials, switch applications to the second, then regenerate the first.
  • Prefer no secret at all. Managed identities and Entra authentication to Azure SQL, Storage and Service Bus mean there is nothing to rotate.

Set an expiration date on secrets, turn on diagnostic logs to send every vault access to Log Analytics (see Azure Monitor, Log Analytics and Application Insights), and alert on unusual reads or on near-expiry.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which statement about Owner or Contributor access to a vault with RBAC authorization is correct?

    Azure separates the management plane from the data plane. An administrator who manages the vault does not get to read its secrets unless a data role is also assigned.
  2. 2. What does purge protection do?

    With purge protection on, soft-deleted items stay recoverable for the whole retention period, even against an administrator. It cannot be turned off afterwards.
  3. 3. How does an App Service app read a secret through a Key Vault reference?

    The platform resolves the reference with the app's identity before the code runs, so the code just reads an ordinary environment variable.
  4. 4. Why does envelope encryption make key rotation cheap?

    The bulk data is encrypted with data keys. Rotating the key encryption key only changes how those small data keys are wrapped.
  5. 5. What is the best way for an application to authenticate to Key Vault?

    A managed identity has no credential to store or rotate. Giving it only the role it needs follows least privilege.

Summary

  • Key Vault stores secrets, keys and certificates; every set creates a new version.
  • Prefer Azure RBAC over access policies, and remember the management plane and the data plane are separate.
  • Applications should authenticate with a managed identity; App Service and Functions can resolve Key Vault references with no SDK code.
  • Turn on soft delete (default) and purge protection, restrict the network, and send diagnostic logs to Log Analytics.
  • Envelope encryption keeps bulk data local and wraps small data keys with a vault key, which makes rotation cheap.
  • Rotate keys by policy, rotate secrets by automation, and prefer designs that need no secret at all.

Next: Azure Monitor, Log Analytics and Application Insights.