How does the [Authorize] attribute interact with Razor Pages, given they don't use the traditional controller/action model?
Short answer
Razor Pages support [Authorize] applied directly to the PageModel class, or more commonly, centralized authorization conventions configured via AddRazorPages().AddPageRoute() or AuthorizeFolder()/AuthorizePage() calls in Program.cs, letting you apply authorization requirements…
Advertisement
AModel answer
Razor Pages support [Authorize] applied directly to the PageModel class, or more commonly, centralized authorization conventions configured via AddRazorPages().AddPageRoute() or AuthorizeFolder()/AuthorizePage() calls in Program.cs, letting you apply authorization requirements to entire folders of pages (like every page under /Admin) without annotating each PageModel individually.
builder.Services.AddRazorPages(options => {
options.Conventions.AuthorizeFolder("/Admin"); // protects every page under /Pages/Admin
options.Conventions.AllowAnonymousToPage("/Admin/Login"); // exception within that folder
});Real-world example
An admin section of a Razor Pages application protects an entire /Admin folder of pages with a single AuthorizeFolder convention call, rather than adding an [Authorize] attribute to every individual PageModel class within that folder.
Likely follow-ups
- How do folder-level conventions interact with page-level [Authorize] attribute overrides?
- What's the equivalent pattern for protecting an entire minimal API route group?
Related topics