In ASP.NET Core, how do you make a protected token such as a booking-change link expire with ITimeLimitedDataProtector, and what happens after expiry?
answer
- wrap an existing IDataProtector
- ToTimeLimitedDataProtector()
- Protect(plaintext, TimeSpan lifetime)
- Unprotect(token, out DateTimeOffset expiration)
- expired: CryptographicException, not null
basics
~10 sCall ToTimeLimitedDataProtector() on an IDataProtector, then Protect(value, TimeSpan.FromHours(24)). Unprotect(token, out expiration) returns the value until then; afterwards it throws CryptographicException ("The payload expired at ..."). The token can still be replayed until it expires.
solid answer
~30 s`ITimeLimitedDataProtector` lives in `Microsoft.AspNetCore.DataProtection` (the Extensions assembly in the shared framework). You get one with `provider.CreateProtector("TravelSite.BookingChange.v1").ToTimeLimitedDataProtector()` and call `Protect(bookingRef, TimeSpan.FromHours(24))` or pass an absolute `DateTimeOffset`. The expiration is written inside the protected payload, so the client cannot extend it. `Unprotect(token, out DateTimeOffset expiration)` checks it against `DateTimeOffset.UtcNow` and throws `CryptographicException` once it has passed. The wrapper appends its own purpose to the chain, so a plain protector with the same purposes cannot read a time-limited payload. Expiry is the only built-in limit: the token is not single-use, and if the keys are lost it dies early.
code
csharp · 26 linesusing System.Security.Cryptography;
using Microsoft.AspNetCore.DataProtection;
public sealed class BookingChangeLinks(IDataProtectionProvider provider)
{
private readonly ITimeLimitedDataProtector _protector = provider
.CreateProtector("TravelSite.BookingChange.v1")
.ToTimeLimitedDataProtector();
public string Create(string bookingRef) =>
_protector.Protect(bookingRef, TimeSpan.FromHours(24));
public bool TryRead(string token, out string bookingRef)
{
try
{
bookingRef = _protector.Unprotect(token, out DateTimeOffset expires);
return true;
}
catch (CryptographicException)
{
bookingRef = "";
return false; // expired, tampered or unknown key
}
}
}go deeper
Remember the two calls: ToTimeLimitedDataProtector() to wrap a protector, and Protect with a TimeSpan lifetime; an expired token throws CryptographicException.
Explain that the expiry is embedded inside the authenticated payload, that the wrapper adds its own purpose, and why that makes plain and time-limited payloads incompatible.
Point out what expiry does not give you: single use, per-token revocation, survival of lost keys and agreement between skewed server clocks, and add server-side state where it matters.
Choose between stateless expiring tokens and server-tracked tokens per flow, weighing replay risk, revocation needs and the operational cost of storing token state.
## The problem it solves Many tokens should stop working after a while: a link to change a booking, a "confirm your email" link, a short-lived download URL. An ordinary `IDataProtector` payload has no expiry of its own; it stays valid for as long as its key stays in the key ring. ASP.NET Core adds **`ITimeLimitedDataProtector`** for this case. It is part of the shared framework (the `Microsoft.AspNetCore.DataProtection.Extensions` assembly), so a `net10.0` web project needs no extra package. ## Creating one You never construct it directly. Wrap a normal protector: ```csharp var protector = provider .CreateProtector("TravelSite.BookingChange.v1") .ToTimeLimitedDataProtector(); ``` The interface adds expiry-aware overloads: | Member | What it does | |---|---| | `Protect(byte[] plaintext, DateTimeOffset expiration)` | protects with an absolute expiry | | `Protect(string plaintext, TimeSpan lifetime)` (extension) | protects with an expiry of now plus `lifetime` | | `Protect(string plaintext, DateTimeOffset expiration)` (extension) | string form of the absolute overload | | `Unprotect(string protectedData, out DateTimeOffset expiration)` | returns the plaintext and reports when it expires | | `CreateProtector(string purpose)` | returns another `ITimeLimitedDataProtector` with an extended chain | The plain `IDataProtector.Protect(byte[])`, called through the interface, uses `DateTimeOffset.MaxValue`, meaning no expiry. ## How the expiry is enforced 1. On `Protect`, the expiration is written as UTC ticks in front of the plaintext, and the combined bytes are protected by the inner protector with one extra purpose appended: `Microsoft.AspNetCore.DataProtection.TimeLimitedDataProtector.v1`. 2. Because the expiry is inside the authenticated payload, a client cannot edit it. 3. On `Unprotect`, the inner protector decrypts and verifies the payload, then the wrapper compares the embedded time with `DateTimeOffset.UtcNow`. 4. If the time has passed, it throws **`CryptographicException`** with the message "The payload expired at ...". Otherwise it strips the header and returns the plaintext. The extra purpose has a consequence: a plain protector with the same chain **cannot** unprotect a time-limited payload, and the time-limited wrapper cannot unprotect a payload made by the plain protector. Mixing the two is a common bug when a team adds expiry to an existing link format. ## What it does not do - **It is not single-use.** Anyone holding the link can use it any number of times until it expires. If a booking-change link must work once, store a nonce or a "used" flag server-side and check it. - **It is not revocable on its own.** To kill one outstanding link early you need server-side state; revoking Data Protection keys kills every payload protected with them. - **It cannot outlive its key.** If the key ring is lost, every outstanding link fails at once, whatever its expiry. - **It relies on server clocks.** On a farm, the instance that unprotects compares against its own clock, so badly skewed instances disagree about the edge. The docs' rule of thumb is to ask whether you can afford for the payload to be permanently unrecoverable after a month; if not, this API is the wrong tool. ## Testing the expiry The wrapper reads `DateTimeOffset.UtcNow` directly; it does not take a `TimeProvider`, so a test cannot fast-forward a fake clock. Two practical approaches: - Protect with an **absolute expiration in the past** (`Protect(value, DateTimeOffset.UtcNow.AddMinutes(-1))`) and assert that `Unprotect` throws `CryptographicException`. - Protect with a future expiration and assert that the `out` parameter of `Unprotect` reports the time you asked for. Use `UseEphemeralDataProtectionProvider()` or `new EphemeralDataProtectionProvider()` in tests so no key files are written. ## For the travel-agency site A booking-change email carries a token valid for 24 hours. The endpoint calls `Unprotect`, catches `CryptographicException` and shows "this link has expired or is invalid", then looks the booking up by reference and still checks that the booking belongs to the signed-in customer, because possession of a valid token proves only that the server issued it.
- How would you make the booking-change link usable only once?Include a random nonce in the protected payload and record it server-side when the link is used, for example in the booking row or a short-lived store keyed by the nonce. On each request, unprotect the token, then reject it if the nonce is already marked as used. `ITimeLimitedDataProtector` bounds how long the link lives; only server state makes it single-use.
- An existing link format used a plain IDataProtector; after switching to ToTimeLimitedDataProtector, every old link fails. Why?The time-limited wrapper appends its own purpose, `Microsoft.AspNetCore.DataProtection.TimeLimitedDataProtector.v1`, to the chain and expects an expiry header inside the payload. Old payloads were protected under the shorter chain, so the new protector cannot unprotect them. Keep the old protector for a transition period, or accept that old links expire.
- Unprotect returns null for an expired time-limited payload.
- A time-limited token becomes invalid after its first successful use.
- The expiry is stored in a separate cookie that the server checks.
- A plain IDataProtector with the same purpose can read a time-limited payload.
- Setting a 30-day lifetime guarantees the token works for 30 days even if keys are lost.