A debugging walk-through for unshared ASP.NET Core Data Protection keys: recognising the symptoms in cookies, antiforgery and OIDC, reading the Data Protection logs, finding where keys are stored per host, and fixing it with a shared, protected key ring and a fixed application name.
Logging everyone out on deploy plus intermittent failures across instances is the signature of a Data Protection key ring that isn't persisted or shared. Cookies, antiforgery tokens and OIDC state are protected with keys; if each container generates its own ring, a cookie issued by instance A can't be unprotected by instance B, and a redeploy throws all rings away.
I confirm it from the logs (key {guid} was not found in the key ring, and the startup warning that keys are stored in an ephemeral folder or without an encryptor), then compare key ids per instance. A second cause is a different application discriminator per host (content root path, slot). The fix is a shared repository such as Azure Blob Storage, keys encrypted with Key Vault, and an explicit SetApplicationName. Sticky sessions only mask it. Expect one last logout on cutover.
"Two symptoms together point me straight at Data Protection. Logout on every deployment means the keys that protect the authentication cookie don't survive the deployment. Intermittent antiforgery failures with three instances means the instances don't share keys: a form rendered by instance A posts to instance B, B can't unprotect the token, and you get a 400. The log line about the key not being found in the key ring confirms it: the payload header names a key id this instance has never seen.
For example, at [company] we moved [a customer portal] from [a single VM] to [AKS with three replicas]. [Around a third of] form posts failed and support was flooded with 'I keep getting logged out'. I pulled the startup logs and saw the Data Protection warning that keys were being stored in a directory inside the container that wouldn't be persisted. I exec'd into two pods, listed the keys folder, and the key GUIDs were different. Someone had turned on session affinity at the ingress as a workaround, which reduced errors but still logged everyone out on each rollout.
The fix was three lines:
PersistKeysToAzureBlobStoragewith the pod's workload identity,ProtectKeysWithAzureKeyVaultso the key XML isn't readable by anyone with blob access, andSetApplicationNameso the discriminator doesn't depend on the container's path. We warned users there'd be one final logout at cutover. [Antiforgery failures went from about 30% to effectively zero, and deployments stopped generating support tickets.]The mistake I see is stopping at sticky sessions, or persisting keys to a shared folder without an encryptor, which means anyone who can read that folder can forge authentication cookies."
| Step | What I look at | What it tells me |
|---|---|---|
| 1 | Startup logs, category Microsoft.AspNetCore.DataProtection |
Ephemeral storage or "No XML encryptor configured" warnings |
| 2 | Error logs | The key {guid} was not found in the key ring, CryptographicException in antiforgery or cookie handlers |
| 3 | Key folder or repository per instance | Different key ids = not shared |
| 4 | Application name / content root per instance and slot | Different discriminators isolate payloads even with a shared ring |
| 5 | Turn off affinity in a test environment | Reproduces cross-instance failures reliably |
| 6 | Redeploy a single instance | Logout confirms keys not persisted |
| Cause | Fix |
|---|---|
| Keys in container file system | Shared repository (Blob, Redis, EF Core) |
| Shared folder, different application name | SetApplicationName("...") |
| App Service slots with separate stores | Shared Blob container for all slots |
| Keys persisted but unencrypted | ProtectKeysWithAzureKeyVault or a certificate |
| Key blob deleted or overwritten | Restore from backup; protect with soft delete and a lock |
After the fix, Data Protection unprotect errors in Application Insights went from [about 2,000 an hour] to [single digits a day], which were genuinely stale cookies from before the cutover, and deploys ran during business hours without user impact.
Checks whether the candidate can map user-visible symptoms to the Data Protection key ring and fix it properly rather than mask it.
Green flags
Red flags
User -> LB -> Pod A: login -> cookie protected with key A1 (header contains A1's id)
User -> LB -> Pod B: request -> look up A1 in B's ring -> not found -> cookie ignored -> 302 to login
Deploy: new pods, new rings A2/B2/C2 -> every existing cookie fails
Cookie authentication treats an unprotectable cookie as no cookie, so users see a login page, not an error. Antiforgery throws, so you see 400s. The OIDC handler fails the callback with 'Correlation failed'.
%LOCALAPPDATA%\ASP.NET\DataProtection-Keys, encrypted with DPAPI.$HOME/.aspnet/DataProtection-Keys, unencrypted, inside the container's writable layer.%HOME%\ASP.NET\DataProtection-Keys, shared across instances of one app but not across slots.Payload isolation includes an application identifier, by default derived from the content root path. Two instances with the same ring but different paths (e.g. different container working directories or slot paths) still can't read each other's payloads. SetApplicationName makes it explicit and stable.
Switching to a new shared ring invalidates every existing cookie once. If you can, first copy one existing key XML into the shared repository so at least sessions issued by that key survive. Rollback to the old config means another logout, so do it once.
Use workload identity for the pod's access to Blob and Key Vault. Avoid a ReadWriteOnce volume shared by replicas. If you use Redis, enable persistence, or a Redis restart becomes a mass logout.
docker exec into each and list ~/.aspnet/DataProtection-Keys.PersistKeysToFileSystem on a shared volume with different SetApplicationName values and observe failures persist; then align the name.PersistKeysToAzureBlobStorage.WebApplicationFactory host and unprotects with another sharing the repository.The fix, plus a startup check that fails fast in non-development environments if the ring isn't persisted.
// Program.cs
using Azure.Identity;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.Extensions.Options;
var credential = new DefaultAzureCredential(); // workload identity in AKS, managed identity in App Service
var dp = builder.Services.AddDataProtection().SetApplicationName("contoso-portal");
if (!builder.Environment.IsDevelopment())
{
dp.PersistKeysToAzureBlobStorage(new Uri(builder.Configuration["DataProtection:BlobUri"]!), credential)
.ProtectKeysWithAzureKeyVault(new Uri(builder.Configuration["DataProtection:KeyUri"]!), credential);
}
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
var km = app.Services.GetRequiredService<IOptions<KeyManagementOptions>>().Value;
if (km.XmlRepository is null || km.XmlEncryptor is null)
throw new InvalidOperationException("Data Protection keys must be persisted and encrypted outside Development.");
}
# Quick evidence from two pods: different key ids = unshared ring
kubectl exec deploy/portal -c app -- ls /root/.aspnet/DataProtection-Keys
kubectl logs -l app=portal --since=1h | grep -E "was not found in the key ring|ephemeral|No XML encryptor"
SetApplicationName. Why it is wrong: different content roots or slots isolate payloads even with a shared repository. Instead: set one explicit name.This bug is a symptom of treating the web tier as stateless while the framework quietly holds state. The broader lesson is to list every piece of hidden per-instance state (Data Protection keys, in-memory caches, local file uploads, SignalR connections) before scaling out, and decide where each lives.
| Approach | When it fits | Cost | When not |
|---|---|---|---|
| Shared ring in Blob + Key Vault | Any multi-instance Azure app | Startup dependencies, RBAC setup | Single-instance dev |
| Redis repository | Existing Redis with AOF/RDB persistence | Redis becomes critical for sign-in | Cache-only Redis without persistence |
| Sticky sessions | Temporary mitigation only | Uneven load, broken on deploy | As the fix |
| Stateless JWT access tokens instead of cookies | APIs, not browser apps with server sessions | Token handling complexity | Browser apps where the BFF and cookies are the safer design |
Operationally, make it observable: a log-based metric for Data Protection unprotect failures (category Microsoft.AspNetCore.DataProtection plus AntiforgeryValidationException) split by instance, an alert when it exceeds a small baseline for 10 minutes, and a deployment annotation so a spike right after a release is obvious. After the fix it should fall to near zero within one cookie lifetime; a later rise usually means someone changed the application name, the storage account or the Key Vault key permissions.
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.
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.
How to tell it (STAR)
**S:** At [company] we moved our [self-service portal] to AKS and users started getting logged out constantly, with [about 30%] of form posts failing. **T:** I took the incident and needed a fix that would hold through deployments, not a workaround. **A:** I found Data Protection's ephemeral-storage warning in the startup logs, proved each pod had different key ids, and showed sticky sessions only hid it. I moved the key ring to Blob Storage protected with a Key Vault key and a fixed application name, removed affinity, and added a startup guard and a cross-host test. **R:** Antiforgery failures dropped to [effectively zero], logouts stopped on deploys, and [logout-related tickets fell from about 40 a week to none].
Last updated 23 Nov 2026.