How to Share ASP.NET Core 10 Data Protection Keys Across Containers Using Redis (2026)

A user signs in on replica A and immediately gets a 401 on replica B. Both replicas use the same authentication scheme, but only A can open its cookie. The usual cause is a separate ASP.NET Core Data Protection key ring on each container. Share one durable ring across the replicas, set a consistent application name, and encrypt the ring with a certificate accessible to each authorized process.

What must replicas share to read a cookie?

A cookie contains a protected authentication ticket. Every replica expected to read it needs compatible application isolation, cookie middleware scheme and settings, and the key material used to protect it. Redis stores a key ring for this lab. Redis does not store a copy of every user’s cookie or automatically revoke a session.

Both replicas use the same protected Redis key ring to validate the cookie.
Both replicas use the same protected Redis key ring to validate the cookie.
Data Where it lives Security consequence
Cookie Browser Keep HTTPS, HttpOnly and a suitable SameSite policy
Data Protection ring Dedicated Redis key Retain old keys required by valid tickets
Key encryption certificate Authorized workload secret mount Restrict private-key access and plan rollover
User identity Authentication system Use real verification and revocation policies

Create a two-replica local lab

Use a .NET 10 SDK, Redis, OpenSSL and a trusted .NET development HTTPS certificate. The project has one Program.cs. Install the Redis storage provider, start a loopback Redis lab, and create a separate password-protected PKCS#12 certificate for the ring. The Kestrel HTTPS certificate and the certificate that encrypts the key ring have different jobs.

BASH
dotnet new web -n SharedCookie -f net10.0
cd SharedCookie
dotnet add package Microsoft.AspNetCore.DataProtection.StackExchangeRedis --version '10.0.*'
dotnet dev-certs https --trust
docker run --rm -p 127.0.0.1:6379:6379 redis:8

In a separate shell create development-only keys. OpenSSL prompts for the PKCS#12 password. Keep these files out of the repository and restrict file permissions. Use a protected secret delivery mechanism for production rather than the export below.

BASH
umask 077
openssl req -x509 -newkey rsa:3072 -sha256 -days 7 -nodes \
  -keyout ring.key -out ring.crt -subj '/CN=Local key ring only'
openssl pkcs12 -export -inkey ring.key -in ring.crt -out ring.pfx
export ConnectionStrings__Redis=localhost:6379
export KeyRing__CertificatePath="$PWD/ring.pfx"
read -rs KeyRing__CertificatePassword
export KeyRing__CertificatePassword ASPNETCORE_ENVIRONMENT=Development

Configure Data Protection and cookie authentication

Replace Program.cs. The development route issues a fixture identity only when the direct peer is loopback and the Development environment is enabled. Keep this lab behind loopback. Never deploy it with that environment behind a local reverse proxy. A production application should remove the fixture route and sign in after real identity verification.

Program.cs
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.DataProtection;
using StackExchange.Redis;

var builder = WebApplication.CreateBuilder(args);
var connection = builder.Configuration.GetConnectionString("Redis")
    ?? throw new InvalidOperationException("Set ConnectionStrings__Redis.");
using var redis = await ConnectionMultiplexer.ConnectAsync(connection);
using var certificate = X509CertificateLoader.LoadPkcs12FromFile(
    builder.Configuration["KeyRing:CertificatePath"]
        ?? throw new InvalidOperationException("Set KeyRing__CertificatePath."),
    builder.Configuration["KeyRing:CertificatePassword"]);
builder.Services.AddDataProtection()
    .SetApplicationName("aspnetpb-cookie-lab")
    .PersistKeysToStackExchangeRedis(redis, "dp:aspnetpb-cookie-lab:v1")
    .ProtectKeysWithCertificate(certificate);
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(o =>
    {
        o.Cookie.Name = "__Host-AspNetPB.Session";
        o.Cookie.Path = "/";
        o.Cookie.SecurePolicy = CookieSecurePolicy.Always;
        o.Cookie.HttpOnly = true;
        o.Cookie.SameSite = SameSiteMode.Lax;
        o.ExpireTimeSpan = TimeSpan.FromMinutes(20);
        o.SlidingExpiration = false;
    });
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
if (app.Environment.IsDevelopment())
{
    // Local fixture only. A real app authenticates the user before creating this ticket.
    app.MapPost("/fixture/sign-in", async (HttpContext ctx) =>
    {
        if (ctx.Connection.RemoteIpAddress is not { } ip ||
            !System.Net.IPAddress.IsLoopback(ip))
            return Results.NotFound();
        var claims = new[] { new Claim(ClaimTypes.NameIdentifier, "demo-account") };
        await ctx.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity(
            claims, CookieAuthenticationDefaults.AuthenticationScheme)));
        return Results.NoContent();
    });
}
app.MapGet("/whoami", (ClaimsPrincipal user) =>
    new { id = user.FindFirstValue(ClaimTypes.NameIdentifier) }).RequireAuthorization();
await app.RunAsync();

The shared application name is a cryptographic isolation input. Keep it consistent between intentional replicas and different across unrelated applications or environments. Give each environment its own Redis key and access policy as well. Using the same name across unrelated apps with the same storage and secrets can destroy a useful isolation boundary.

Verify handoff between replicas

Start one process with dotnet run --no-launch-profile --urls https://localhost:5068, and another on https://localhost:5168 using the same environment and storage. Cookies are host scoped and do not use the port as a boundary. These commands assume curl trusts the local HTTPS certificate.

BASH
curl -i -c cookies.txt -X POST https://localhost:5068/fixture/sign-in
curl -i -b cookies.txt https://localhost:5168/whoami

Expect 204 from the fixture and 200 with {"id":"demo-account"} from replica B. An unauthenticated call must fail its authorization policy, although the response can vary between a redirect and 401 depending on the endpoint metadata and cookie events. As a negative control run B with a different application name and repeat. The ticket should no longer authenticate. Remove the cookie file and development certificate after the lab.

Operate a durable key ring

Use Redis persistence and replication suited to key storage. A volatile, evictable cache is a poor home for keys that protect authentication cookies. Restrict the Redis account to its required operations and environment. Keep the connection private and authenticated, with TLS and certificate validation as appropriate. Monitor for failed ring reads and ticket decryption, but never log raw cookies or keys.

Before rotating the certificate, deploy readers that can decrypt both old and new ring entries. New keys should use the new certificate while old certificates remain available for reading existing entries. Plan backups and disaster recovery with both the ring and encryption keys. A restored ring without its private key cannot decrypt prior cookies.

No. Cookie lifetime and key lifetime are separate. Keep old keys for as long as protected payloads may require them. A lost key can invalidate more than cookies, including antiforgery or other Data Protection payloads.

Why do cookies work on one replica only?

Compare scheme, application name, ring location and cookie host/path. Then verify certificate private-key access on the failing container. A cookie with Secure set also needs HTTPS.

Trace a failed deployment before replacing the key ring

Check the cookie in the browser first. If it was never sent, verify host scope, HTTPS, path, SameSite, and whether a recent sign-in actually set it. If it arrived but only one container rejects it, compare the runtime version, middleware scheme and application name on both replicas. Then check the Redis key name and whether both identities can read it. A missing certificate private key can make a Redis ring look healthy while ticket decryption still fails.

Verify a rollout with a cookie minted before the deployment and one minted during it. The earlier cookie should be readable while its ticket is valid. Verify restart recovery and a Redis failover before removing a certificate or old key. Avoid exposing the key-ring XML in application logs. Track failed ticket validation and Redis errors separately so a certificate issue is distinguishable from a storage outage.

A key ring protects several framework features. If one service should issue cookies and another should be unable to issue or read them, keep the key rings and credentials separate. If the sign-in mechanism needs centrally enforced logout, use an explicit session validation or revocation strategy. Cookie sharing handles compatibility between replicas. It does not implement revocation.

Takeaway. Test one cookie across replicas before and after a restart, and treat the Redis key, encryption certificate and cookie settings as one deployment contract.

References

Comments