skip to content

In ASP.NET Core Data Protection, what happens when the default key reaches its 90-day lifetime, and why do existing auth cookies keep working?

level: middleimportance: should knowfreq 35%

answer

  1. one default key protects, all keys unprotect
  2. NewKeyLifetime 90 days, minimum 7
  3. successor created 2 days before expiry
  4. key ring refresh about every 24 hours
  5. IDeletableKeyManager since .NET 9

basics

~20 s

About two days before the default key's 90-day expiry, ASP.NET Core writes a successor that activates when the old key expires. Old keys stay in the ring and can still unprotect, so cookies protected with them keep working.

solid answer

~50 s

Data Protection protects every new payload with the ring's **default key** and writes that key's id into the payload; `Unprotect` looks the id up in the whole ring. `KeyManagementOptions.NewKeyLifetime` is 90 days (set it with `SetDefaultKeyLifetime`; anything under 7 days throws `ArgumentOutOfRangeException`). When the default key will expire within two days and no successor exists, the system writes a new key whose activation date is the old key's expiration, giving other instances time to load it at their periodic key ring refresh (about every 24 hours). After the switch, new cookies use the new key, but the expired key is not removed, so older cookies still unprotect until the cookie's own ticket expires. Expired keys only stop protecting; revocation is what stops unprotecting. In ASP.NET Core 10, keys are never deleted automatically, though `IDeletableKeyManager.DeleteKeys` (added in 9) can remove them.

code

csharp · 17 lines
csharp
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.DataProtection.KeyManagement;

builder.Services.AddDataProtection()
    .SetApplicationName("travel-site")
    .PersistKeysToFileSystem(new DirectoryInfo("/mnt/shared/dp-keys"))
    .SetDefaultKeyLifetime(TimeSpan.FromDays(30));

var app = builder.Build();

// Admin inspection: list the ring and see which key protects new data
var keyManager = app.Services.GetRequiredService<IKeyManager>();
foreach (IKey key in keyManager.GetAllKeys())
{
    app.Logger.LogInformation("{KeyId} active {Activation} expires {Expiration} revoked {Revoked}",
        key.KeyId, key.ActivationDate, key.ExpirationDate, key.IsRevoked);
}

go deeper

for a junior

Remember that keys last 90 days by default and that rotation does not log users out, because old keys still decrypt.

for a middle

Explain the default key versus the whole ring, the two-day successor and activation delay, the 24-hour refresh, and the 7-day minimum lifetime.

for a senior

Separate expired, revoked and deleted keys, know when DisableAutomaticKeyGeneration is right, and check from logs that all instances see the same default key.

for a principal

Set rotation policy against exposure per key, key-ring growth and the business cost of unreadable payloads, rather than lengthening lifetimes to hide storage problems.

## The key ring and the default key Data Protection keeps a **key ring**: a set of keys, each stored as an XML element (a `key-{guid}.xml` file in a folder repository) with a creation, activation and expiration date. At any moment one key is the **default key**. - `Protect` always uses the default key and writes its **key id** into the payload header. - `Unprotect` reads the id and looks that key up in the **whole ring**, default or not. That split is the whole answer to "why don't cookies break at rotation": rotating changes which key protects new data, not which keys can read old data. ## The numbers | Setting | Default | How to change it | |---|---|---| | Lifetime of a new key | **90 days** | `SetDefaultKeyLifetime(TimeSpan)` or `KeyManagementOptions.NewKeyLifetime`; under 7 days throws `ArgumentOutOfRangeException` | | Lead time for the successor | 2 days before the default key expires | fixed | | Activation delay of a normal new key | 2 days after creation | fixed | | Key ring refresh | about every 24 hours, or when the default key expires | fixed | | Automatic key generation | on | `DisableAutomaticKeyGeneration()` or `KeyManagementOptions.AutoGenerateKeys` | ## What happens near day 90 1. When the default key will expire within two days and the ring has no key that will be active after it, the system writes a new key with an **activation date equal to the old key's expiration** and a 90-day expiration. 2. Other instances sharing the ring load the new key at their next refresh. The two-day lead exists so that every instance knows the key before anyone uses it, otherwise an instance could receive a payload protected with a key it has never seen. 3. At the old key's expiration the new key becomes the default; cookies issued from then on are protected with it. 4. The old key stays in the ring, **expired but usable for `Unprotect`**. There is one exception to the two-day delay: if the ring is empty or every key has expired (an app that was switched off for months), a new key is created with **immediate** activation. ## Expired, revoked and deleted are different - **Expired**: no longer used to protect; still unprotects. Normal and harmless. - **Revoked** (`IKeyManager.RevokeKey` or `RevokeAllKeys`): `Unprotect` throws for payloads protected with it. Used after a compromise. - **Deleted**: gone from storage, so its payloads are unrecoverable. Before ASP.NET Core 9 keys could not be deleted by design. Since 9, `IDeletableKeyManager` (`CanDeleteKeys`, `DeleteKeys(Func<IKey, bool>)`, implemented by `XmlKeyManager`) allows it for very long-running services; the docs still recommend not deleting keys, because each one is small. How long a payload lives is decided by its consumer, not by the key: the cookie handler's ticket expiry, or the expiry an `ITimeLimitedDataProtector` embeds. A cookie issued on day 89 of a key's life works on day 91 if its ticket is still valid. ## When to change the defaults - **A shorter key lifetime** (for example 30 days) limits how much data any one key protects. It does not shorten cookie lifetimes and creates more keys. - **`DisableAutomaticKeyGeneration()`** belongs on an app that only reads a ring another app writes, such as a back-office tool sharing the booking site's ring, so that exactly one app creates keys. If that writer stops running, the reader keeps using an expired default key, because the fallback never invents one. - **Do not set a very long lifetime to "avoid rotation problems"**: rotation is not the cause of logouts; missing shared storage is. ## Inspecting the ring `IKeyManager.GetAllKeys()` returns every key as an `IKey` with `KeyId`, `CreationDate`, `ActivationDate`, `ExpirationDate` and `IsRevoked`. Logging these at startup on each instance, as the code example does, is the quickest way to prove that all instances read the same ring and agree on which key is the default.

  • Why does a new key normally wait two days before it becomes the default?
    Instances cache the key ring and refresh it about every 24 hours. If a new key became the default immediately, one instance could protect a cookie with a key that the others have not loaded yet, and they would fail to read it. The two-day delay guarantees every instance has loaded the key before anyone uses it.
  • What happens if every instance runs with DisableAutomaticKeyGeneration() and the last key expires?
    No instance creates a successor, so the system falls back to the most recently activated non-revoked key and keeps protecting with it even though it has expired. Nothing breaks immediately, but rotation has silently stopped. If the ring is empty or every key is revoked, initialisation fails instead.

A hotel re-codes its keycard system every few months: new cards are cut with the new code, but each door lock keeps a list of older codes it still accepts, so a guest's card from last week still opens the room. Only removing a code from the locks, the equivalent of revoking a key, stops old cards working.

  • When a Data Protection key expires, every cookie protected with it stops working.
  • SetDefaultKeyLifetime also controls how long auth cookies stay valid.
  • ASP.NET Core deletes expired keys automatically after 90 days.
  • An expired key and a revoked key behave the same for Unprotect.
  • Every new key becomes the default the moment it is created, even during normal rotation.

Assumes ASP.NET Core 10; key deletion through IDeletableKeyManager.DeleteKeys exists only since ASP.NET Core 9, and earlier versions kept every key forever.