Construct an AuthorizationHandlerContext directly with a test ClaimsPrincipal, the requirement instance, and (for resource-based handlers) a test resource object, then call the handler's HandleRequirementAsync method directly and assert on context.HasSucceeded -- testing the authorization logic in isolation without spinning up a full ASP.NET Core test server.
[Fact]
public async Task Handler_Succeeds_ForResourceOwner() {
var user = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim("sub", "user1") }));
var document = new Document { OwnerId = "user1" };
var requirement = new OwnerRequirement();
var context = new AuthorizationHandlerContext(new[] { requirement }, user, document);
await new OwnerAuthorizationHandler().HandleRequirementAsync(context, requirement, document);
Assert.True(context.HasSucceeded);
}
Real-world example
A test suite for a resource-based OwnerAuthorizationHandler directly verifies both the success case (matching owner) and failure case (non-owner) without needing WebApplicationFactory or a real HTTP request, keeping the tests fast and focused.
Likely follow-ups
When would you need a full integration test instead of this isolated handler unit test?
How do you test a policy composed of multiple requirements together?
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?
Endpoint MetadataRoute Constraints & TemplatesControllers vs Minimal APIs
Instead of hardcoding every policy's logic in Program.cs, store permission definitions and role-to-permission mappings in a database, then implement a custom IAuthorizationHandler that checks a generic "HasPermission" requirement against the database-driven mapping (often cached for performance) -- letting administrators add, modify, or remove permissions and role assignments through an admin UI without requiring a code deployment for every permission change.
public class PermissionRequirement : IAuthorizationRequirement { public string Permission { get; } public PermissionRequirement(string p) => Permission = p; }
public class PermissionHandler : AuthorizationHandler<PermissionRequirement> {
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement) {
var userId = context.User.FindFirst("sub")?.Value;
if (await _permissionService.UserHasPermissionAsync(userId, requirement.Permission))
context.Succeed(requirement);
}
}
Real-world example
An enterprise SaaS platform lets customer administrators define custom roles with granular permission sets through a self-service admin UI, with the ASP.NET Core authorization system checking against this database-driven permission model rather than a fixed set of code-defined policies.
Likely follow-ups
How do you efficiently cache permission lookups to avoid a database call on every authorization check?
How does this dynamic model interact with the declarative [Authorize(Policy=...)] attribute syntax?
User.IsInRole("Admin") is the imperative, programmatic equivalent of the declarative [Authorize(Roles = "Admin")] attribute -- both check whether the ClaimsPrincipal contains a role claim matching the given value, but IsInRole is used inline within action/endpoint logic when the decision needs to happen conditionally rather than as a blanket endpoint-level restriction.
[HttpGet]
public IActionResult GetReport() {
if (User.IsInRole("Admin")) {
return Ok(_fullReport); // admins see everything
}
return Ok(_summaryReport); // everyone else sees a limited view
}
Real-world example
A reporting endpoint returns a full detailed report for Admin users and a redacted summary for everyone else, using an inline IsInRole check rather than needing two entirely separate endpoints with different [Authorize(Roles=...)] restrictions.
Likely follow-ups
When is inline IsInRole preferable to splitting into separate authorized endpoints?
How does IsInRole handle a user with multiple roles?
By default, all requirements added to a single AuthorizationPolicy must succeed (AND logic) for the policy to pass -- calling RequireClaim, RequireRole, and RequireAssertion multiple times on the same policy builder adds multiple requirements that ALL must be satisfied; achieving OR logic between alternatives requires either a single RequireAssertion with custom OR logic inside it, or defining separate policies checked independently.
builder.Services.AddAuthorization(options => {
options.AddPolicy("SeniorManager", policy => policy
.RequireRole("Manager") // AND
.RequireClaim("years", "5", "10", "15", "20")); // must ALSO have 5+ years
// OR logic requires a single assertion instead:
options.AddPolicy("ManagerOrAdmin", policy => policy
.RequireAssertion(ctx => ctx.User.IsInRole("Manager") || ctx.User.IsInRole("Admin")));
});
Real-world example
A policy requiring both a Manager role AND a minimum tenure claim correctly rejects a newly-promoted manager who hasn't yet met the tenure requirement, since both requirements must independently succeed under the default AND evaluation.
Likely follow-ups
How would you debug why a policy with multiple requirements unexpectedly fails?
What's a cleaner way to express complex OR logic than a single large RequireAssertion?