Skip to content

Avoid ClaimsPrincipal.Claims iterator allocations in ClaimsAuthorizationRequirement - #70221

Merged
halter73 merged 1 commit into
mainfrom
perf/auth-claims-requirement
Nov 3, 2026
Merged

halter73 merged 1 commit into
mainfrom
perf/auth-claims-requirement

Conversation

@davidfowl

Copy link
Copy Markdown
Member

Avoid ClaimsPrincipal.Claims iterator allocations in ClaimsAuthorizationRequirement

  • You've read the Contributor Guide and Code of Conduct.
  • You've included unit or integration tests for your change, where applicable.
  • You've included inline docs for your change, where applicable.
  • There's an open issue for the PR that you are making. (Perf finding, no separate issue.)

Make RequireClaim(...) evaluation about 35% faster with fewer allocations.

Description

Problem

ClaimsAuthorizationRequirement.HandleRequirementAsync runs for every RequireClaim(...) policy check, so it runs on every request to such endpoints. It enumerates context.User.Claims. ClaimsPrincipal.Claims is a compiler-generated iterator that flattens Identities and each identity's Claims. Enumerating it allocates the outer iterator plus the nested Identities and per-identity enumerators, about 136 B per check, and adds two levels of interface dispatch per claim.

Change

  • If context.User is exactly ClaimsPrincipal, so Claims and Identities aren't overridden, enumerate user.Identities and then each identity.Claims directly. That is the same sequence ClaimsPrincipal.Claims produces. identity.Claims is still called virtually, so derived ClaimsIdentity types behave as before.
  • Derived ClaimsPrincipal types keep using the virtual Claims property exactly as before.
  • IList<T> sources are indexed rather than enumerated.
  • The match predicate is unchanged: claim type OrdinalIgnoreCase, and if values were specified, value Ordinal via AllowedValues.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.AuthorizeAsync with a principal carrying 16 claims, comparing RequireClaim("permission", "admin", "write") with RequireClaim("permission"). BenchmarkDotNet with [MemoryDiagnoser], in-process, 3 warmup and 15 measured iterations, 3 interleaved A/B rounds:

Round Benchmark main PR
1 RequireClaimWithValues 472.7 ns, 768 B 292.9 ns, 632 B
1 RequireClaim 509.7 ns, 768 B 289.9 ns, 632 B
2 RequireClaimWithValues 467.3 ns, 768 B 319.9 ns, 632 B
2 RequireClaim 494.0 ns, 768 B 304.1 ns, 632 B
3 RequireClaimWithValues 446.1 ns, 768 B 302.8 ns, 632 B
3 RequireClaim 481.1 ns, 768 B 295.6 ns, 632 B

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_SearchesAllIdentities
  • Authorize_RequireClaim_UsesOverriddenPrincipalClaims: a derived ClaimsPrincipal overriding Claims is still honored.
  • Authorize_RequireClaim_UsesOverriddenIdentityClaims: a derived ClaimsIdentity overriding Claims is still honored.

Microsoft.AspNetCore.Authorization.Test: 175 passed, 0 failed (net12.0).

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

…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>
Copilot AI balanced review requested due to automatic review settings November 1, 2026 15:02
@github-actions github-actions Bot added the area-auth Includes: authentication, authorization, OAuth, OIDC, and access token validation label Nov 1, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 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 ClaimsPrincipal instances 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

@PureWeen

PureWeen commented Nov 1, 2026

Copy link
Copy Markdown
Member

/review

Copy link
Copy Markdown
Member Author

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 user.GetType() == typeof(ClaimsPrincipal), so neither Claims nor Identities can be overridden. On that exact type, ClaimsPrincipal.Claims has the same implementation in .NET Framework and dotnet/runtime. In both, it is foreach (identity in Identities) foreach (claim in identity.Claims) yield return claim, which is the same traversal the fast path performs (still calling the virtual identity.Claims). The IList checks are only type tests, with a foreach fallback, and the handler only asks whether any claim matches, so enumeration order can't change the result. That covers the net462 and netstandard2.0 builds too. The test project targets only net12.0, so those builds aren't exercised at runtime here.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

@halter73 halter73 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@halter73
halter73 merged commit a2d0307 into main Nov 3, 2026
29 checks passed
@halter73
halter73 deleted the perf/auth-claims-requirement branch November 3, 2026 20:00
@halter73
halter73 temporarily deployed to copilot-pat-pool November 3, 2026 20:00 — with GitHub Actions Inactive
@halter73
halter73 temporarily deployed to copilot-pat-pool November 3, 2026 20:01 — with GitHub Actions Inactive
@halter73
halter73 temporarily deployed to copilot-pat-pool November 3, 2026 20:03 — with GitHub Actions Inactive
@halter73
halter73 temporarily deployed to copilot-pat-pool November 3, 2026 20:05 — with GitHub Actions Inactive
@halter73
halter73 temporarily deployed to copilot-pat-pool November 3, 2026 20:06 — with GitHub Actions Inactive
@halter73
halter73 temporarily deployed to copilot-pat-pool November 3, 2026 20:07 — with GitHub Actions Inactive
@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

✅ 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

  • Conceptual article: Not required — Internal perf optimization of RequireClaim evaluation; no user-visible behavior or API change.
  • Migration guidance: Not required — No upgrade action needed.
  • Breaking change: Not required — No compatibility impact; semantics preserved.

Copy link
Copy Markdown
Member Author

@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:

Match position Allowed values main PR Allocated main → PR
Early (index 0) no 45.7 / 44.8 / 46.4 6.2 / 6.4 / 6.2 136 B → 0 B
Early (index 0) yes 52.3 / 53.6 / 52.0 12.5 / 12.5 / 12.6 136 B → 0 B
Late (index 15, as in the PR benchmark) no 128.7 / 131.1 / 125.9 26.5 / 26.8 / 26.8 136 B → 0 B
Late (index 15) yes 145.6 / 143.5 / 145.9 37.8 / 37.8 / 37.3 136 B → 0 B
No match (worst case, full 16-claim scan) no 144.2 / 145.8 / 146.9 27.6 / 27.8 / 27.8 136 B → 0 B
No match (worst case) yes 135.2 / 138.2 / 135.8 27.6 / 27.7 / 27.7 136 B → 0 B

Method: BenchmarkDotNet A/B of the HandleRequirementAsync matching logic only, without AuthorizeAsync overhead. One version is copied verbatim from merge-base 4f556f73, the other from PR head 86a69f49. Both run against the same ClaimsPrincipal (one identity, 16 claims) and a real ClaimsAuthorizationRequirement("permission", …). Main and PR returned the same result in all 6 configurations. In absolute terms, the early-match saving is about 40 ns plus 136 B per evaluated requirement.

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)

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — 86a69f49 Deployed Nov 3, 2026 by halter73 via conclusion #177
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-auth Includes: authentication, authorization, OAuth, OIDC, and access token validation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants