Three load-balanced instances of an ASP.NET Core travel-agency site log every user out on each deploy; why, and how do you configure Data Protection to stop it?
answer
- auth cookie is protected, not stored
- $HOME/.aspnet/DataProtection-Keys inside each container
- one shared repository: PersistKeysTo*
- SetApplicationName, else content root path
- ProtectKeysWithCertificate for keys at rest
basics
~20 sEach container keeps its own Data Protection keys in its filesystem, so cookies from one instance fail on another and all fail after a redeploy. Persist keys to shared storage, protect them at rest, and set one application name.
solid answer
~40 sThe auth cookie, antiforgery tokens and TempData cookies are Data Protection payloads, and with no configuration each container stores its key ring under `$HOME/.aspnet/DataProtection-Keys` in its own filesystem (the framework even logs a warning that the keys may not outlive the container). So instance A cannot read cookies from B, and a redeploy throws every key away; the cookie handler logs "Unprotect ticket failed" and treats users as anonymous. The fix is `builder.Services.AddDataProtection().SetApplicationName("travel-site")` plus one shared repository, such as `PersistKeysToDbContext<TContext>()`, `PersistKeysToStackExchangeRedis(...)` or `PersistKeysToFileSystem` on a shared volume, and `ProtectKeysWithCertificate(cert)`, because a custom repository turns off automatic at-rest encryption. Setting the name matters because the default application discriminator is the content root path, which can differ between instances or releases.
code
csharp · 17 linesusing Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.DataProtection.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
builder.Services.AddDbContext<KeysDbContext>(o =>
o.UseNpgsql(builder.Configuration.GetConnectionString("Keys")));
builder.Services.AddDataProtection()
.SetApplicationName("travel-site")
.PersistKeysToDbContext<KeysDbContext>()
.ProtectKeysWithCertificate(builder.Configuration["DataProtection:CertThumbprint"]!);
public sealed class KeysDbContext(DbContextOptions<KeysDbContext> options)
: DbContext(options), IDataProtectionKeyContext
{
public DbSet<DataProtectionKey> DataProtectionKeys => Set<DataProtectionKey>();
}go deeper
Know that auth cookies are encrypted with Data Protection keys and that every instance must use the same keys for a user to stay signed in.
Describe the default key locations, why a container's location is lost on redeploy, and the PersistKeysTo* and SetApplicationName calls that fix it.
Diagnose the logout from the logs (container-folder warning, unencrypted-key warning, Unprotect ticket failed), roll out shared keys with an encryptor, and plan for the one final logout.
Treat the key store as critical state: choose its storage, backup, certificate rotation and access control as deliberately as the database's.
## Why every deploy logs everyone out By default, cookie authentication keeps no server-side session: the auth cookie *is* the signed-in identity, protected with Data Protection. A request is signed in only if the instance that receives it can unprotect that cookie, and two things decide that: **which keys** the instance holds, and **which application name** it protects under. With no configuration, each process picks a key repository by itself: 1. On a few hosting platforms, a platform-specific shared folder the framework detects. 2. If a user profile is available: `%LOCALAPPDATA%\ASP.NET\DataProtection-Keys` on Windows (keys encrypted at rest with DPAPI) or `$HOME/.aspnet/DataProtection-Keys` on Linux and macOS (not encrypted). 3. On Windows without a loaded profile (typically IIS): a registry key under HKLM, DPAPI-encrypted. 4. Otherwise an in-memory repository; the framework warns that protected data becomes unavailable when the process exits. Three Linux containers fall into case 2, each writing keys into its **own** filesystem. When the framework knows it runs in a container (the official images set `DOTNET_RUNNING_IN_CONTAINER`) and the folder is not a mounted volume, it logs the warning event `UsingEphemeralFileSystemLocationInContainer`: keys "may not be persisted outside of the container". For the travel-agency site that means: - **Every instance has a different key ring.** A cookie issued by instance A fails on B and C, so users appear randomly signed out depending on where the load balancer sends them. - **Every deploy replaces the containers** and their keys, so every outstanding cookie fails at once. Half-filled booking forms fail antiforgery validation and TempData messages vanish too. Nothing crashes: the cookie handler logs "Unprotect ticket failed" and treats the request as anonymous, which is why this is often misdiagnosed as a cookie-expiry problem. ## The second trap: the application name The provider prefixes every purpose chain with an **application discriminator**. Unless you call `SetApplicationName`, it is `IHostEnvironment.ContentRootPath` with a trailing separator. Identical containers all run from `/app/`, but instances deployed to different folders, or a release process that unpacks each version into a new directory, change the discriminator. Shared keys then still cannot read each other's cookies. ## The fix | Call | Package | Notes | |---|---|---| | `PersistKeysToFileSystem(DirectoryInfo)` | shared framework | a network share or volume every instance mounts | | `PersistKeysToDbContext<TContext>()` | `Microsoft.AspNetCore.DataProtection.EntityFrameworkCore` | the context implements `IDataProtectionKeyContext` (`DbSet<DataProtectionKey> DataProtectionKeys`) and needs a migration for that table | | `PersistKeysToStackExchangeRedis(IConnectionMultiplexer, RedisKey)` | `Microsoft.AspNetCore.DataProtection.StackExchangeRedis` | default key name `DataProtection-Keys`; the Redis data must not be evicted or lost | | `PersistKeysToRegistry(RegistryKey)` | shared framework | Windows only, one machine, so no help for a farm | Choosing a repository yourself **disables automatic encryption at rest**. New keys are written as plain XML and each one logs the warning "No XML encryptor configured. Key ... may be persisted to storage in unencrypted form." Add an encryptor: - `ProtectKeysWithCertificate(X509Certificate2)` works on any OS; every instance needs the certificate with its private key. - The thumbprint overload, `ProtectKeysWithCertificate(string)`, looks the certificate up in the CurrentUser and then LocalMachine personal stores, accepts only a certificate that validates, and throws `InvalidOperationException` at the call if none is found, so an untrusted self-signed certificate fails there. - `ProtectKeysWithDpapi()` and `ProtectKeysWithDpapiNG()` are Windows-only. ## Why sticky sessions are not the fix Session affinity on the load balancer hides the first symptom: a user keeps hitting the instance that issued the cookie. It fixes nothing else. A redeploy still replaces every container and its keys, a scale-in moves users to an instance that cannot read their cookie, and antiforgery tokens rendered by one instance still fail if the post lands elsewhere. Affinity also unbalances load. Shared keys make every instance interchangeable, which is the property a farm needs. ## Rolling it out 1. Deploy shared storage, the certificate and a fixed application name together. Users are logged out **one last time**, because their cookies were protected with the old per-container keys. 2. From then on the first instance to need a key writes it to the shared store and the others load it, so deploys and scale-outs keep everyone signed in. 3. Verify in the logs: no container-folder warning, no unencrypted-key warning, and the same key id used by every instance. If the store is ever lost or emptied, the same mass logout returns, so back up the key store and the certificate with the same care as the database.
- The instances now share a key folder, yet users are still logged out after each release. What do you check first?Whether `SetApplicationName` is set. Without it the discriminator is the content root path, and a release process that deploys to a new directory changes it every time. Next check that every instance really writes to the same location and can read the certificate's private key, and compare the key ids the instances log.
- Why does a single Windows server not show this problem when the same app is moved to containers?On Windows with a loaded user profile, keys go to `%LOCALAPPDATA%\ASP.NET\DataProtection-Keys` on the machine's disk and survive redeploys of the app files. In a container, `$HOME/.aspnet/DataProtection-Keys` lives in the container's own filesystem, which is discarded when the container is replaced.
- What changes if the shared key ring is stored in Redis that is configured as an evicting cache?`PersistKeysToStackExchangeRedis` stores the whole key ring under one Redis key (`DataProtection-Keys` by default). If Redis evicts or loses that key, every instance generates new keys and every cookie and antiforgery token fails again. Use Redis with persistence and no eviction for that key, or a database or volume.
- Data Protection keys are derived from the server's TLS certificate, so instances share them automatically.
- Sticky sessions on the load balancer fully fix the logouts on deploy.
- PersistKeysToFileSystem still encrypts keys with DPAPI by default on Linux.
- Users logged out after a deploy means the cookie ExpireTimeSpan is too short.
- Instances with the same keys accept each other's cookies even with different content roots and no SetApplicationName.