ASP.NET Core uses Data Protection to protect authentication cookies, antiforgery tokens, TempData, and application data created through IDataProtector. The default configuration is often sufficient for a single development process. It becomes unsafe operationally when the application runs on several instances, behind a load balancer, or inside short-lived containers.
A common symptom is that a user logs in successfully but is asked to sign in again on the next request. Another symptom is that every active user is logged out after a deployment. These incidents are frequently mistaken for session, database, or load-balancer problems. In many cases, the real cause is that each application instance has a different Data Protection key ring.
The real problem: separate key rings per instance
Assume that an application runs on two servers named web-01 and web-02. A user signs in through web-01. The authentication cookie is protected with keys available to that instance. If the next request is routed to web-02, the second server must be able to read the same key ring to validate the cookie.
If each server has its own local key store, web-02 cannot decrypt or validate data protected by web-01. The result may be an anonymous request, a redirect to the login page, or an antiforgery validation failure. Because the behavior depends on which node receives the request, the problem can appear intermittent.
The same issue occurs after a container restart when keys are stored only in the container’s writable layer. A replacement container starts with a new key ring and cannot read cookies created by the previous container. Users are then logged out after an otherwise successful deployment.
What Data Protection protects
Data Protection is designed for trusted state that is generated by the server and later returned through an untrusted client. Authentication cookies are the most visible example, but they are not the only one. Antiforgery tokens, TempData, and custom protected payloads may also depend on the key ring.
Two design questions must be separated:
- Key-ring sharing: Can all instances read the same key history?
- Protection at rest: Are the stored keys protected from unauthorized access?
Putting keys in a shared directory may solve interoperability but still leave the key material exposed to every identity that can read that directory. A production design must address both availability and access control.
Persist the key ring outside the application process
For a single machine or a controlled development environment, a shared file-system location can be sufficient. The following example stores keys in a persistent directory and gives the application a stable name:
using Microsoft.AspNetCore.DataProtection;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDataProtection()
.PersistKeysToFileSystem(
new DirectoryInfo("/var/lib/myapp/dataprotection-keys"))
.SetApplicationName("MyCompany.MyApp");
builder.Services.AddAuthentication();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();The directory must be reachable by every instance that participates in the same application deployment. On Linux, grant read, write, and create permissions only to the account running the application. On Windows, restrict the directory to the application pool identity or service account.
Do not store the key ring only in a container layer. Use a persistent volume, a shared file system, or an external storage provider. Otherwise, deleting the container also deletes the keys and invalidates all protected data that depends on them.
Keep the application name stable
SetApplicationName contributes to application isolation. Applications that must share authentication cookies need a consistent application name, a common key store, and compatible authentication configuration. Applications that must remain isolated should use different names or separate key rings.
For example, staging and production should normally not share the same authentication boundary. A test cookie created in staging should not be accepted by production. Separate storage locations and distinct application names make that boundary explicit.
Protect keys at rest
The key-ring directory is part of the application’s security boundary. An attacker who obtains the key material may be able to process protected payloads or undermine the confidentiality and integrity guarantees expected by the application. File permissions are therefore as important as the encryption mechanism used for the files.
A certificate can be used to protect keys stored on disk:
using System.Security.Cryptography.X509Certificates;
using Microsoft.AspNetCore.DataProtection;
var certificate = new X509Certificate2(
"/etc/myapp/certificates/dataprotection.pfx",
builder.Configuration["DataProtection:CertificatePassword"]);
builder.Services.AddDataProtection()
.PersistKeysToFileSystem(
new DirectoryInfo("/var/lib/myapp/dataprotection-keys"))
.ProtectKeysWithCertificate(certificate)
.SetApplicationName("MyCompany.MyApp");Never commit the certificate password to source control. Use a secret manager, an operating-system secret store, or a managed cloud secret service. Certificate rotation also requires planning: the old certificate may still be needed to decrypt existing key files while new keys are protected with the replacement certificate.
Choosing storage for a web farm
ASP.NET Core supports several approaches for sharing the key ring. The right choice depends on availability requirements, backup capabilities, latency, and operational ownership.
| Approach | Suitable scenario | Main concern |
|---|---|---|
| Shared file system | Instances on the same network | Permissions and volume durability |
| Database | An existing central persistence layer | Database availability and access scope |
| Redis | Low-latency shared access | Persistence, backup, and failover settings |
| Cloud blob storage | Managed, externally accessible storage | Identity permissions and key encryption |
Do not assume that every Redis deployment is suitable for key storage. The selected configuration must provide durable persistence and an appropriate backup strategy. If the key ring is lost, existing cookies and other protected payloads may no longer be readable.
Common mistakes
- Creating a new key directory on every deployment: Existing cookies become unreadable.
- Writing keys inside the container: Keys disappear when the container is replaced.
- Granting broad access to a shared directory: The application’s security boundary becomes unnecessarily large.
- Sharing staging and production keys: Environment isolation is weakened.
- Relying only on sticky sessions: Failover, maintenance, or routing changes can still expose the underlying problem.
- Changing the application name unexpectedly: Applications may stop accepting protected data even when they use the same physical key store.
Test the failure modes, not just login
A successful login test is not enough. Run two instances simultaneously, authenticate through one node, and send subsequent requests to the other node. Then restart one node and verify that the existing authentication cookie still works.
A deployment validation checklist should include:
- Can a new instance read a cookie created by an older instance?
- Can an older instance read data protected by the new instance?
- Does the key ring remain available after a process or container restart?
- Are storage permissions limited to the application identity?
- Is the key ring included in backup and recovery procedures?
- Does a staging-to-production deployment preserve the intended environment boundary?
For diagnosis, temporarily increase the logging level for Microsoft.AspNetCore.DataProtection. This can reveal key-storage and initialization problems. Avoid logging key contents or secrets in production; log only operational failures, storage paths where appropriate, and access problems.
Sharing cookies between applications
If several ASP.NET Core applications are intentionally designed to share authentication cookies, they need more than a common directory. The applications should use the same cookie name, compatible authentication scheme, common application name, and common Data Protection keys. They should also use compatible user and claim configuration.
This is useful for a deliberate single sign-on design, but it should not be enabled simply to hide an incorrectly configured deployment. Sharing a cookie creates a trust relationship between applications and should be treated as a security decision.
Conclusion
The default local key store can be acceptable for a single-instance development application. It is not a complete production design for a load-balanced, containerized, or web-farm deployment. Production systems should use a persistent key ring accessible to all intended instances, restrict access to the application identity, protect keys at rest, separate environments, and include the key store in backup and recovery planning.
When these requirements are treated as part of deployment architecture rather than as an afterthought, intermittent logouts, invalid antiforgery tokens, and post-deployment authentication failures become predictable and preventable.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/
- https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/overview?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/web-farm?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/security/cookie-sharing?view=aspnetcore-8.0
0 Comments