If your ASP.NET Core app on Azure App Service randomly logs everyone out — or breaks anti-forgery tokens — after every deployment or restart, and there's no error message telling you why, there's a good chance the culprit is where your Data Protection keys are stored.
The symptom
Everything works fine right after a deploy. Then, at some point — after a restart, a scale event, or the next deployment — users start getting logged out unexpectedly, or you see anti-forgery token validation failures with no obvious cause. There's no clear exception pointing at the real problem. Cookies just silently stop validating.
The wrong assumption
The natural assumption is that ASP.NET Core's Data Protection system — which encrypts things like auth cookies and anti-forgery tokens — just works out of the box in Azure App Service, the same way it does in local development.
By default, it doesn't persist the way you'd expect in a cloud hosting environment.
The actual cause
ASP.NET Core's Data Protection system generates a set of cryptographic keys used to protect cookies and tokens. If those keys aren't stored somewhere stable, every time the app restarts, scales out to another instance, or gets redeployed, it can end up with a different set of keys than before — which means anything encrypted with the old keys (existing auth cookies, anti-forgery tokens) suddenly fails to validate. Azure App Service's default file system behavior doesn't guarantee key persistence across these events the way a traditional single-server deployment would.
The fix
Explicitly persist the Data Protection keys to a stable location — the App Service's HOME directory works well, since it's persisted storage that survives restarts and deployments:
services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(
Environment.GetEnvironmentVariable("HOME") + @"\ASP.NET\DataProtection-Keys"))
.SetApplicationName("YourAppName");
Setting an explicit ApplicationName is also worth doing — it keeps the key ring scoped correctly if you ever have multiple apps sharing the same underlying storage.
The broader lesson
Anywhere your ASP.NET Core app runs across multiple instances, restarts, or redeployments — which is essentially every cloud hosting scenario — Data Protection key persistence isn't optional, even though the framework won't warn you about it. The failure mode is especially nasty because there's no exception with a clear cause; it just looks like intermittent, unexplainable auth problems. If you're seeing silent logouts or anti-forgery failures that seem to correlate with deploys or restarts, this is the first place to look.
Top comments (0)