Covers ASP.NET Core Data Protection: the consumers that depend on it, the key ring and automatic 90-day rotation, purpose strings, time-limited protectors, default key storage locations, and production configuration with PersistKeysToAzureBlobStorage, ProtectKeysWithAzureKeyVault and SetApplicationName.
Data Protection is ASP.NET Core's built-in API for encrypting and authenticating short-lived payloads the app hands to clients and gets back. It protects authentication cookies, antiforgery tokens, TempData, OIDC state and Identity tokens. You call IDataProtectionProvider.CreateProtector("purpose"), and the purpose string isolates consumers so one feature's payload can't be replayed into another.
Under the hood is a key ring: keys with a 90-day default lifetime, rotated automatically, old keys retained to unprotect older payloads. The production trap is storage: by default keys live on the local machine or, in a container, in an ephemeral folder, so each instance and each redeploy has different keys and users get logged out. Fix it with PersistKeysToAzureBlobStorage, ProtectKeysWithAzureKeyVault and the same SetApplicationName everywhere. Don't use it for long-term data at rest.
"Data Protection is the cryptography layer ASP.NET Core uses whenever it gives a client something it must get back unmodified: the authentication cookie, antiforgery tokens, TempData in cookies, the OpenID Connect state and nonce, and Identity's email confirmation and password reset tokens. I can use it directly too: inject
IDataProtectionProvider, create a protector with a purpose string like"Invoices.DownloadLink.v1", and callProtectandUnprotect. The purpose is mixed into key derivation, so a payload protected for one purpose won't unprotect under another, which stops a password-reset token being reused as a download link.The mechanics are a key ring. Each key has a 90-day lifetime by default. The system creates the next key ahead of expiry, new payloads use the default key, and the key id is in every payload header so older payloads still unprotect with older keys. Each payload is AES-256-CBC encrypted and HMACSHA256 authenticated with subkeys derived from the master key and the purpose.
The thing that bites teams is where the keys live. On IIS they're in the registry or user profile; in a Linux container they end up in a folder that disappears with the container, and ASP.NET Core logs a warning about it. With three instances behind a load balancer, each has its own key ring, so a cookie issued by instance A fails on instance B. In Azure I configure
PersistKeysToAzureBlobStorageso every instance shares the ring,ProtectKeysWithAzureKeyVaultso the key XML is encrypted at rest with a Key Vault key, and an explicitSetApplicationNameso a new deployment slot or container name doesn't isolate the keys.The mistake I see is using Data Protection to encrypt database columns for years. If keys are revoked or the ring is lost, that data is gone. It's designed for transient payloads."
| Consumer | What is protected | Symptom when keys aren't shared |
|---|---|---|
| Cookie authentication | The authentication ticket | Users logged out on redeploy or between instances |
| Antiforgery | Cookie token and request token | AntiforgeryValidationException, 400s on form posts |
| TempData (cookie provider) | TempData values | TempData silently empty |
| OIDC handler | state, nonce cookie |
"Correlation failed" / "Unable to unprotect the message.State" |
| Identity token providers | Email confirmation, password reset tokens | "Invalid token" |
| Host | Default | Production choice |
|---|---|---|
| IIS | Registry (HKLM) or user profile | Shared storage if web farm |
| Azure App Service | %HOME%\ASP.NET\DataProtection-Keys, shared across instances of one app but not slots |
Blob + Key Vault for slots and multiple apps |
| Containers / AKS | In-memory or ephemeral folder | Blob Storage + Key Vault, or a Redis/EF Core repository |
After a move to [AKS with three replicas], [about a third] of form posts failed antiforgery validation and users were logged out on every deployment. Sharing the key ring in Blob Storage protected by Key Vault took the antiforgery error rate from [around 30%] to [effectively zero] the same day.
Checks whether the candidate understands what Data Protection does, how the key ring works and how to configure it correctly for multi-instance production.
Green flags
Red flags
| magic header (4) | key id GUID (16) | encrypted payload (IV + ciphertext + HMAC) |
^ tells Unprotect which key in the ring to use
The master key is never used directly. For each payload: subkeys = KDF(masterKey, purposes, random key modifier) using SP800-108 CTR-HMACSHA512, then AES-256-CBC + HMACSHA256 by default (or AES-GCM via UseCryptographicAlgorithms).
day 0 key A created, default
day 88 key B created (activation date = A's expiry)
day 90 B becomes default; A expired but kept for Unprotect
revoked key can no longer unprotect anything
Keys are XML files in the repository (file system, Blob, Redis, EF Core DataProtectionKeys table). The key encryptor protects the XML at rest (DPAPI, a certificate, or Key Vault).
CreateProtector("A").CreateProtector("B") is the purpose chain ["A", "B"]. The application name (or by default the content root path) is the root discriminator, which is why two apps sharing a ring still can't read each other's payloads unless they set the same SetApplicationName, and why changing paths between deployments breaks old payloads.
protector.ToTimeLimitedDataProtector().Protect(value, lifetime: TimeSpan.FromMinutes(15)) embeds an expiry checked on unprotect. Good for signed download links and invitation tokens.
Azure.Extensions.AspNetCore.DataProtection.Blobs and Azure.Extensions.AspNetCore.DataProtection.Keys.PersistKeysToFileSystem on a mounted volume and repeat.encryptedSecret element).Production Data Protection setup for multiple instances, plus a purpose-scoped, time-limited protector for download links.
// Program.cs
using Azure.Identity;
using Microsoft.AspNetCore.DataProtection;
var credential = new DefaultAzureCredential(); // managed identity in Azure
builder.Services.AddDataProtection()
.SetApplicationName("contoso-portal") // same value on every instance and slot
.PersistKeysToAzureBlobStorage(
new Uri(builder.Configuration["DataProtection:BlobUri"]!), credential)
.ProtectKeysWithAzureKeyVault(
new Uri(builder.Configuration["DataProtection:KeyUri"]!), credential)
.SetDefaultKeyLifetime(TimeSpan.FromDays(90)); // the default, shown explicitly
builder.Services.AddSingleton<DownloadLinks>();
using Microsoft.AspNetCore.DataProtection;
namespace Portal.Documents;
public sealed class DownloadLinks(IDataProtectionProvider provider)
{
// Purpose string versioned so a format change doesn't accept old links.
private readonly ITimeLimitedDataProtector _protector =
provider.CreateProtector("Portal.Documents.DownloadLink.v1").ToTimeLimitedDataProtector();
public string Create(Guid documentId, string userId) =>
_protector.Protect($"{documentId:N}|{userId}", lifetime: TimeSpan.FromMinutes(15));
public (Guid DocumentId, string UserId)? Read(string token)
{
try
{
var parts = _protector.Unprotect(token).Split('|');
return (Guid.ParseExact(parts[0], "N"), parts[1]);
}
catch (System.Security.Cryptography.CryptographicException)
{
return null; // tampered, expired or from another purpose
}
}
}
SetApplicationName.ProtectKeysWithAzureKeyVault or a certificate.IKeyManager if compromised, and back up the container.Data Protection is shared infrastructure, so treat the key ring as a production dependency: its storage needs access control, backup and monitoring, and its application name is part of your compatibility contract. If you ever suspect the ring leaked, revoking keys logs everyone out and invalidates all tokens, which is the correct trade-off but needs a comms plan.
| Repository | When it fits | Cost | When not |
|---|---|---|---|
| Azure Blob + Key Vault | Azure, multiple instances or slots | Two dependencies at startup | Offline or on-prem only |
EF Core PersistKeysToDbContext |
You already have a shared database | Keys in the same DB as data | When DB compromise must not enable cookie forgery (add an encryptor) |
| Redis | Existing Redis, containers | Redis persistence must be on | Redis without persistence |
| File system on a shared volume | On-prem web farms | Volume management | Ephemeral containers |
Measure: unprotect failures in logs (Microsoft.AspNetCore.DataProtection category), antiforgery 400 rate after deployments, and alerts if the key blob changes unexpectedly.
After a successful login the app calls HttpContext.SignInAsync: the cookie handler serialises the ClaimsPrincipal into an authentication ticket, encrypts and signs it with Data Protection, and sends it as a cookie. On each request the handler decrypts the cookie and rebuilds HttpContext.User, with no database call.
HttpOnly (JavaScript can't read it), Secure (HTTPS only), SameSite=Lax by default (not sent on most cross-site requests).ExpireTimeSpan (default 14 days) with sliding expiration that reissues the cookie once half the window has passed; IsPersistent decides whether it survives closing the browser.The trade-off: a self-contained cookie is fast and stateless, but you can't revoke it without extra checks or a server-side ticket store.
HMAC-SHA256 is a keyed hash: the sender computes HMAC(secret, message) and you recompute it with the same secret. A match proves the body wasn't altered and came from someone holding the secret; it does not encrypt anything.
Three details make verification correct. Hash the raw request bytes exactly as received, because re-serialising JSON changes whitespace and ordering. Compare with CryptographicOperations.FixedTimeEquals, because an early-exit comparison leaks how many leading bytes matched through timing. And sign a timestamp with the payload and reject old ones (Stripe uses a 5-minute default) so a captured request can't be replayed; store event ids for idempotency too. Keep the secret in Key Vault and accept two during rotation. Use asymmetric signatures instead when many parties must verify but shouldn't be able to forge.
How to tell it (STAR)
**S:** At [company] our [staff portal] started throwing 'Correlation failed' during sign-in after we scaled out and added a staging slot. **T:** I had to find out why sign-in broke intermittently and fix it before [the next release]. **A:** From the logs I saw the OIDC state couldn't be unprotected, compared key ids, and found each slot had its own Data Protection key ring. I moved the ring to Blob Storage protected with a Key Vault key, set a fixed application name, and added a test that unprotects across two hosts. **R:** Sign-in failures dropped from [about 4%] to [under 0.01%], and slot swaps no longer logged anyone out.
Last updated 23 Nov 2026.