How do you unit test custom authorization handlers in isolation, without needing a full HTTP request pipeline?
Short answer
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…
Advertisement
AModel answer
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?
Related topics