⚙️ Fix Output Caching Serving a Stale Authorized Page
The Output Caching middleware caches a response keyed, by default, on the request path and query string only — it does not automatically vary that key by the authenticated user unless a policy explicitly tells it to. If `[OutputCache]` or a matching cache policy is applied to a route that renders user-specific, authorized content, the FIRST user to hit that route after the cache is empty gets their personalized response cached under that shared path+query key, and every DIFFERENT user hitting the same URL within the cache’s expiration window is served that first user’s page verbatim.
🔎 The Problem
builder.Services.AddOutputCache(options =>
{
options.AddPolicy("PerUser", policy =>
policy.SetVaryByHeader("Cookie")
.Expire(TimeSpan.FromSeconds(30)));
});
// ...
app.MapGet("/dashboard", DashboardHandler)
.CacheOutput("PerUser"); // without a vary rule, every user shares one entry
✅ Fix: Vary the Cache Key by Who’s Asking
- Never apply a blanket `[OutputCache]` attribute or a catch-all cache policy to a route group without checking whether every route in that group is actually anonymous, static content — a single authorized endpoint swept in by a broad policy is enough to leak another user’s page.
- For any endpoint that legitimately needs caching AND varies by user, add an explicit `VaryByValue` keyed on the user’s id or claims, rather than `VaryByHeader(“Cookie”)` alone, which varies correctly but can fragment the cache badly if session cookies are unique per request.
- Add an integration test that hits a cached, authorized endpoint as two different authenticated users in sequence and asserts the second response actually contains the second user’s data — this is the one test that catches exactly this bug.
🚨 Why This Is Dangerous
- A personalized page served to the wrong logged-in user isn’t a cosmetic glitch — depending on what the page shows, it can be an active information-disclosure incident the moment a second user loads that URL, with nothing in a typical error log to flag it.
A cache key that ignores who’s asking will happily hand your page to whoever asks next.
Related posts:

ASP.NET Core: Fix an Authorize Policy That Silently Never Runs Because It Was Applied to a Minimal A...

ASP.NET Core: Fix Localization Falling Back to the Default Culture Because the Accept-Language Heade...
