Repository navigation
Avoid ClaimsPrincipal.Claims iterator allocations in ClaimsAuthorizationRequirement - #70221
Conversation
…ionRequirement ClaimsPrincipal.Claims flattens all identities' claims through a compiler generated iterator that also allocates enumerators for Identities and each identity's Claims. When the principal is exactly ClaimsPrincipal (Claims and Identities are not overridden), enumerate each identity's Claims directly, which is equivalent. Derived principals keep using the virtual Claims property. Also index IList<Claim> sources instead of allocating an enumerator. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🔵 Needs a closer look
The fast path depends on runtime-specific claims enumeration, but only net12.0 tests are reported and equivalence across other supported runtimes remains unverified.
No open issues 🎉
What changed in this PR
Optimizes RequireClaim(...) policy evaluation by reducing claim-iteration overhead while retaining the virtual Claims path for derived principals.
Changes:
- Traverses identities directly for exact
ClaimsPrincipalinstances and indexes list-backed collections. - Adds tests for multiple identities, case sensitivity, and overridden claims properties.
- Adds authorization benchmarks for requirements with and without allowed values.
| File | Description |
|---|---|
src/Security/perf/Microbenchmarks/ClaimsAuthorizationRequirementBenchmark.cs |
Adds timing and allocation benchmarks for claim requirements. |
src/Security/Authorization/test/DefaultAuthorizationServiceTests.cs |
Covers identity traversal, matching rules, and overridden claims. |
src/Security/Authorization/Core/src/ClaimsAuthorizationRequirement.cs |
Adds optimized traversal and shared claim-matching helpers. |
Review effort: Balanced
|
/review |
|
Replying to the Copilot review note about whether the fast path behaves the same on other runtimes: it doesn't depend on runtime-specific behavior. It only runs when 🤖 Posted by ASP.NET Core Perf 2 (AI Agent) |
halter73
left a comment
There was a problem hiding this comment.
Non-blocking: The matching claims are near the end of a 16-claim identity, so the benchmark favors a long scan. An early-match case would help show how much of the improvement carries over to shorter searches.
|
✅ No documentation PR was created. Confidence that documentation is needed: 5% No docs needed: implementation-only performance improvement with no public or observable behavior change. Documentation surfaces considered
|
|
@halter73 here's the early-match case you asked for. Most of the improvement still holds for short searches. When the matching claim is the first of the 16 claims, the handler logic drops from about 46 ns to 6 ns (no values) and from about 52 ns to 12.5 ns (with allowed values). The 136 B iterator allocation goes away in every case. Mean ns for rounds 1 / 2 / 3:
Method: BenchmarkDotNet A/B of the Machine: BenchmarkDotNet 0.15.2, AMD EPYC 9V74 (2 vCPU), Ubuntu 24.04 container, .NET SDK 10.0.403 / runtime 10.0.14, Server GC. 3 rounds, 3 warmup + 12 iterations each. Verdict: a win in all three positions. The early-match case is still about 4–7x faster with zero allocations. 🤖 Posted by ASP.NET Core Perf 2 (AI Agent) |
Avoid ClaimsPrincipal.Claims iterator allocations in ClaimsAuthorizationRequirement
Make
RequireClaim(...)evaluation about 35% faster with fewer allocations.Description
Problem
ClaimsAuthorizationRequirement.HandleRequirementAsyncruns for everyRequireClaim(...)policy check, so it runs on every request to such endpoints. It enumeratescontext.User.Claims.ClaimsPrincipal.Claimsis a compiler-generated iterator that flattensIdentitiesand each identity'sClaims. Enumerating it allocates the outer iterator plus the nestedIdentitiesand per-identity enumerators, about 136 B per check, and adds two levels of interface dispatch per claim.Change
context.Useris exactlyClaimsPrincipal, soClaimsandIdentitiesaren't overridden, enumerateuser.Identitiesand then eachidentity.Claimsdirectly. That is the same sequenceClaimsPrincipal.Claimsproduces.identity.Claimsis still called virtually, so derivedClaimsIdentitytypes behave as before.ClaimsPrincipaltypes keep using the virtualClaimsproperty exactly as before.IList<T>sources are indexed rather than enumerated.OrdinalIgnoreCase, and if values were specified, valueOrdinalviaAllowedValues.Contains(value, StringComparer.Ordinal). The first match still short-circuits.There are no public API or behavior changes, and nothing is cached. The project still builds for net462, netstandard2.0 and net12.0.
Benchmarks
New
ClaimsAuthorizationRequirementBenchmark:IAuthorizationService.AuthorizeAsyncwith a principal carrying 16 claims, comparingRequireClaim("permission", "admin", "write")withRequireClaim("permission"). BenchmarkDotNet with[MemoryDiagnoser], in-process, 3 warmup and 15 measured iterations, 3 interleaved A/B rounds:That's about 35–40% faster and 136 B (18%) less allocated per authorization check. The remaining allocations come from
AuthorizationHandlerContext, the result and the handler pipeline, which this PR doesn't touch.Tests
New tests in
DefaultAuthorizationServiceTests:Authorize_RequireClaim_SearchesAllIdentities: the match is in the third identity, with an empty identity in between. Covers case-insensitive type matching and case-sensitive value matching.Authorize_RequireClaimWithNoValues_SearchesAllIdentitiesAuthorize_RequireClaim_UsesOverriddenPrincipalClaims: a derivedClaimsPrincipaloverridingClaimsis still honored.Authorize_RequireClaim_UsesOverriddenIdentityClaims: a derivedClaimsIdentityoverridingClaimsis still honored.Microsoft.AspNetCore.Authorization.Test: 175 passed, 0 failed (net12.0).🤖 Posted by ASP.NET Core Perf 2 (AI Agent)