📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

After every deployment of your ASP.NET Core app, all users are logged out, and with three instances behind a load balancer you see intermittent antiforgery errors and 'The key {guid} was not found in the key ring' in the logs. How do you diagnose and fix it?

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.

Senior Debugging Advanced aspnet-core cryptography data-protection debugging kubernetes security

🎯 Key points

  • Symptom pattern: logout on redeploy plus intermittent failures across instances = key ring not shared or not persisted
  • Ephemeral container storage: keys live in the writable layer ($HOME/.aspnet/DataProtection-Keys) and vanish on every restart, so every cookie and token becomes undecryptable
  • Log evidence: 'key {guid} was not found in the key ring', 'Unable to unprotect', startup warnings about ephemeral storage or no XML encryptor
  • Second cause: application discriminator differs (content root path, slot) without SetApplicationName
  • Fix: PersistKeysToAzureBlobStorage + ProtectKeysWithAzureKeyVault + SetApplicationName; Redis only with persistence, EF Core only with an encryptor
  • Protect the repository: soft delete, resource lock, backup; losing it is a mass logout
  • Sticky sessions hide but don't fix it; expect one final logout at cutover and communicate it
  • Operate it: alert on unprotect error rate per instance and after each deployment; cross-host unprotect test in CI

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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: PersistKeysToAzureBlobStorage with the pod's workload identity, ProtectKeysWithAzureKeyVault so the key XML isn't readable by anyone with blob access, and SetApplicationName so 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."


Diagnosis steps

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

Causes and fixes

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

Production example

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.

🔍 What the interviewer is checking

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

  • Connects logout-on-deploy and cross-instance antiforgery errors to Data Protection
  • Uses logs and per-instance key ids as evidence
  • Fixes with shared storage, encryption at rest and application name
  • Rejects sticky sessions as a fix and plans the cutover

Red flags

  • Blames cookie expiry or the load balancer only
  • Disables antiforgery
  • Shares keys without protecting them

📚 Learn in depth

1. Why the symptoms look like this

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'.

2. Where keys go by default

  • Windows/IIS with a loaded user profile: %LOCALAPPDATA%\ASP.NET\DataProtection-Keys, encrypted with DPAPI.
  • IIS without a profile: registry, or in-memory.
  • Linux: $HOME/.aspnet/DataProtection-Keys, unencrypted, inside the container's writable layer.
  • Azure App Service: %HOME%\ASP.NET\DataProtection-Keys, shared across instances of one app but not across slots.

3. The application discriminator

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.

4. Cutover and rollback

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.

5. Kubernetes specifics

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.

Try it yourself

  1. Run two containers of the same app behind a simple nginx round-robin, sign in, and refresh until you get logged out.
  2. docker exec into each and list ~/.aspnet/DataProtection-Keys.
  3. Add PersistKeysToFileSystem on a shared volume with different SetApplicationName values and observe failures persist; then align the name.
  4. Switch to Azurite (local Blob emulator) with PersistKeysToAzureBlobStorage.
  5. Write an integration test that protects with one WebApplicationFactory host and unprotects with another sharing the repository.

💻 Code

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"

⚠ Common mistakes

  • Mistake: Enabling sticky sessions as the fix. Why it is wrong: deployments and scale-in still invalidate every cookie, and failover breaks sessions. Instead: share the key ring.
  • Mistake: Sharing keys on a volume without an XML encryptor. Why it is wrong: anyone who reads the folder can forge authentication cookies. Instead: protect keys with Key Vault or a certificate.
  • Mistake: Forgetting SetApplicationName. Why it is wrong: different content roots or slots isolate payloads even with a shared repository. Instead: set one explicit name.
  • Mistake: Increasing cookie lifetime to "reduce logouts". Why it is wrong: the cookie isn't expiring; it can't be decrypted. Instead: fix key persistence.
  • Mistake: Disabling antiforgery validation to stop the 400s. Why it is wrong: it reopens CSRF. Instead: fix the shared ring.
  • Mistake: Persisting keys to Redis without persistence. Why it is wrong: a Redis restart logs everyone out. Instead: Blob Storage, or Redis with AOF/RDB persistence.
  • Mistake: Cutting over without telling users or support. Why it is wrong: one guaranteed logout looks like a new incident. Instead: schedule and communicate it.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the key ring or PersistKeysToAzureBlobStorage. Why: Checks deeper understanding of Data Protection purposes, key lifetime and consumers.
    How to answer

    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.

  2. When: Candidate explains that the authentication cookie can't be decrypted. Why: Checks cookie authentication internals: flags, expiry and revocation.
    How to answer

    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.

    • Flags: HttpOnly (JavaScript can't read it), Secure (HTTPS only), SameSite=Lax by default (not sent on most cross-site requests).
    • Expiry: 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.
    • Keys: every instance must share the Data Protection key ring, or cookies issued by one server can't be read by another.

    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.

🛠 Real-world problems: how you handle them

Mass logouts and antiforgery failures after moving to AKS
Situation
A [customer self-service portal] (Razor Pages, cookie auth, about [15,000 daily users]) moved from [one Windows VM] to [AKS with three replicas] in Australia East.
Signals
Support tickets about repeated logouts; antiforgery `400 Bad Request` rate around [30%] of form posts; logs with `The key {guid} was not found in the key ring`; every rollout caused a spike in sign-ins.
Investigation
Application Insights failures blade filtered on `AntiforgeryValidationException`; startup logs showing the ephemeral key storage warning; `kubectl exec` listing different key files per pod; confirmed ingress session affinity had been added as a workaround.
Resolution
Configured `PersistKeysToAzureBlobStorage` with workload identity, `ProtectKeysWithAzureKeyVault`, and `SetApplicationName`; removed session affinity; scheduled the cutover with a support notice about one final sign-in.
Prevention
Startup check that throws outside Development if keys aren't persisted and encrypted; integration test protecting on one host and unprotecting on another; alert on Data Protection unprotect errors; resource lock and soft delete on the key container.

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].

More in Cryptography

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me