⚙️ Fix Razor Pages Page Filter Running Before Auth
A custom IPageFilter or IAsyncPageFilter registered globally in Razor Pages runs as part of the MVC filter pipeline, and its OnPageHandlerSelectionAsync stage executes before authorization filters get their turn in the default pipeline ordering — code in that filter that assumes HttpContext.User is already the authenticated user (reading claims, checking roles) can run against an anonymous or stale principal if authorization hasn’t actually completed yet.
🔎 The Problem
public class AuditPageFilter : IAsyncPageFilter
{
public async Task OnPageHandlerSelectionAsync(PageHandlerSelectedContext context)
{
var userId = context.HttpContext.User.FindFirst("sub")?.Value;
// userId is null here - this stage runs before the
// Authorize filter has populated the authenticated principal
_audit.Log(userId, context.HandlerMethod.MethodInfo.Name);
}
public Task OnPageHandlerExecutionAsync(...) => next();
}
✅ Fix: Move the Logic to a Stage That Runs After Authorization
- Do the claims-dependent work in
OnPageHandlerExecutionAsyncinstead ofOnPageHandlerSelectionAsync— by that stage, authorization has already run andHttpContext.Userreflects the real authenticated principal. - If the filter genuinely needs to run at selection time, read only resource-identifying information there and defer anything claims-based to a later stage or to the action itself.
- Add an explicit null check and a logged warning when
User.Identity.IsAuthenticatedis false at the point your filter runs, so a pipeline-ordering mistake like this surfaces immediately instead of silently loggingnullforever.
🚨 Why This Is Dangerous
- Because the filter doesn’t throw an exception, this produces plausible-looking audit log entries with a null actor instead of an obvious failure — it can go unnoticed for a long time in log review.
Page filter stages run in a fixed order whether or not your code’s assumptions do — know which side of authorization your filter actually sits on.




