⚙️ New Server = Invalid Antiforgery Token
A form that worked fine yesterday suddenly throws Antiforgery token validation failed right after a deploy or scale-out — even though nothing about the form itself changed.
🐞 The Problem
User loads the page (server A issues an antiforgery cookie + token). Load balancer routes the POST to server B. Server B can't decrypt server A's token -> validation fails -> users see a confusing error on a form that "should just work."
🔍 Why This Happens
By default, ASP.NET Core's Data Protection keys (which encrypt antiforgery tokens, cookies, etc.) are generated per-machine and stored locally. Scale out to multiple instances or redeploy a container without persistent storage, and each instance has a DIFFERENT key ring -- so a token issued by one is garbage to another.
✅ The Fix: Share the Data Protection Key Ring
- Persist keys to a location every instance can read: a shared file path, Azure Blob Storage, or Redis.
- Set the same applicationName across all instances so keys aren’t partitioned per app.
- Do this BEFORE your first scale-out, not after users start reporting it.
🔑 Shared Key Ring (Program.cs)
builder.Services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(@"\\shared\keys"))
.SetApplicationName("MyApp");
// Or, for containers/cloud:
builder.Services.AddDataProtection()
.PersistKeysToStackExchangeRedis(redisConnection, "DataProtection-Keys")
.SetApplicationName("MyApp");
Antiforgery errors right after a deploy are almost never a code bug in the form — they’re a five-minute Data Protection configuration fix that most teams only discover the hard way, in production.

