Skip to content

Materialize trimmed [Authorize] roles once in AuthorizationPolicy.CombineAsync - #70183

Merged
DeagleGross merged 4 commits into
mainfrom
perf/authz-roles
Nov 6, 2026
Merged

DeagleGross merged 4 commits into
mainfrom
perf/authz-roles

Conversation

@davidfowl

@davidfowl davidfowl commented Oct 31, 2026 •

Copy link
Copy Markdown
Member

Materialize trimmed [Authorize] roles once in AuthorizationPolicy.CombineAsync

  • 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 from end-to-end profiling, no separate issue.)

Stop re-running the lazy [Authorize(Roles = ...)] query on every request.

Description

AuthorizationPolicy.CombineAsync passed a lazy Where/Select query to RequireRole, and RolesAuthorizationRequirement stored it as AllowedRoles. The combined policy is cached per endpoint (AuthorizationPolicyCache in AuthorizationMiddleware, and MVC's AuthorizeFilter), so every authorization check re-ran the query. Each run allocated the iterator, re-ran IsNullOrWhiteSpace and called Trim() again, which allocates a new string for every role with surrounding spaces. End-to-end profiling with dotnet-trace showed this ArrayWhereSelectIterator<string, string> on every request.

The fix materializes the query once with .ToArray() when the policy is built. Roles, order, whitespace-entry skipping and the InvalidOperationException for an all-whitespace Roles are unchanged. There are no public API changes.

Tests:

  • AuthorizationPolicyFacts.CombineTrimsRolesOnceAndPreservesOrder checks order and trimming, and that repeated enumeration returns the same string instances. It fails on main.
  • AuthorizationPolicyFacts.CombineThrowsForRolesWithOnlyWhitespaceEntries pins the existing exception behavior.
  • Microsoft.AspNetCore.Authorization.Test: 169/169 passed.

Benchmark

src/Security/perf/Microbenchmarks/AuthorizeRolesBenchmark.cs builds policies once with CombineAsync from [Authorize(Roles = "Admin,User")] and [Authorize(Roles = "Manager, Editor, User")], then calls IAuthorizationService.AuthorizeAsync for a user in role User. "main" is the merge base 4f556f7. "Earlier PR" is the previous revision of this PR (9dd2ee5: custom trim helper plus a string[] fast path in RolesAuthorizationRequirement). "This PR" is .ToArray() only. Runs were interleaved (main, earlier PR, this PR) ×3.

Method Round main Earlier PR This PR (.ToArray())
AuthorizeAsync_Roles 1 270.3 ns ± 23.1 251.5 ns ± 16.9 248.6 ns ± 14.7
AuthorizeAsync_Roles 2 287.5 ns ± 12.5 260.8 ns ± 15.9 269.8 ns ± 14.0
AuthorizeAsync_Roles 3 265.4 ns ± 13.2 253.1 ns ± 14.0 267.9 ns ± 21.5
AuthorizeAsync_RolesWithSpaces 1 312.1 ns ± 10.3 277.9 ns ± 15.8 281.3 ns ± 24.0
AuthorizeAsync_RolesWithSpaces 2 319.0 ns ± 21.9 280.7 ns ± 15.8 305.0 ns ± 38.2
AuthorizeAsync_RolesWithSpaces 3 320.4 ns ± 17.1 278.2 ns ± 10.3 284.5 ns ± 22.1
Method main alloc Earlier PR alloc This PR alloc
AuthorizeAsync_Roles 768 B 712 B 744 B
AuthorizeAsync_RolesWithSpaces 880 B 752 B 784 B

Averaged over rounds, this PR is −4.5% time / −24 B for Roles = "Admin,User" and −8.5% time / −96 B for the spaced list. The earlier revision's extra time gain is within the error bars. Its only consistent extra is the 32 B array enumerator, which isn't worth the extra hot-path code.

Machine: AMD EPYC 9V74, 2 cores, Linux; .NET SDK 12.0.100-alpha.1.26521.103, .NET 12.0.0 (12.0.26.52911) X64 RyuJIT, Server GC. BenchmarkDotNet --config perflab (in-process), --warmupCount 3 --iterationCount 10, MemoryDiagnoser. All builds use identical benchmark source.

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

…bineAsync

CombineAsync stored a lazy Where/Select query over the split Roles string in the
RolesAuthorizationRequirement. Because the combined policy is cached per endpoint
(AuthorizationPolicyCache / MVC AuthorizeFilter), the query was re-evaluated on
every authorization check, allocating iterators and re-trimming role names
(e.g. " User".Trim()) per request. Materialize the trimmed roles into an array once,
and iterate arrays directly in RolesAuthorizationRequirement.HandleRequirementAsync.

Co-authored-by: Copilot <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 31, 2026 15:33
@github-actions github-actions Bot added the area-auth Includes: authentication, authorization, OAuth, OIDC, and access token validation label Oct 31, 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.

🟢 Approval recommended

No active review issues remain for the authorization role-processing optimization.

No open issues 🎉

What changed in this PR

This PR reduces repeated work in ASP.NET Core authorization by materializing trimmed role names when a policy is built and avoiding array-enumerator allocations during role checks.

Changes:

  • Store filtered, trimmed roles once, preserving order and existing empty-role validation.
  • Iterate role arrays directly while retaining live enumeration for other collections.
  • Add tests for trimming, repeated string-instance reuse, whitespace-only input, and non-array role checks.
File Description
src/​Security/​Authorization/​test/​DefaultAuthorizationServiceTests.cs Tests matching and nonmatching roles through the non-array fallback.
src/​Security/​Authorization/​test/​AuthorizationPolicyFacts.cs Tests role order, trimming, string-instance reuse, and whitespace-only rejection.
src/​Security/​Authorization/​Core/​src/​RolesAuthorizationRequirement.cs Adds direct array iteration while preserving the enumerable fallback.
src/​Security/​Authorization/​Core/​src/​AuthorizationPolicy.cs Materializes filtered, trimmed roles into an array during policy construction.

Review effort: Balanced

@PureWeen

PureWeen commented Nov 1, 2026

Copy link
Copy Markdown
Member

/review

@DeagleGross

Copy link
Copy Markdown
Member

The root cause is that the lazy Where/Select query is stored as AllowedRoles and re-run on every check of the cached policy. Could we fix just that by materializing it once with .ToArray()?

var trimmedRolesSplit = rolesSplit.Where(r => !string.IsNullOrWhiteSpace(r)).Select(r => r.Trim()).ToArray();
policyBuilder.RequireRole(trimmedRolesSplit);

It runs once per endpoint, so the extra allocation doesn't matter. It removes the per-request iterator and the repeated IsNullOrWhiteSpace/Trim(), and it replaces the 30-line TrimRoles helper with one call. The empty-roles InvalidOperationException behavior is unchanged.

I'd also drop all changes from RolesAuthorizationRequirement. It only saves the enumerator allocation, and it adds code to a hot path. If you have numbers showing it's worth it, please share the benchmark with and without that change; With NET10+ capabilities around array enumeration de-abstraction saving a enumerator may not even be worth it: .NET 10 runtime release notes: https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotnet-10/runtime. See the "Array interface method devirtualization" and "Array enumeration de-abstraction" sections.

@davidfowl davidfowl added the agent:working An AI agent is actively working on this issue/PR label Nov 6, 2026 — with Copilot SWE Agent
…irement change

Per review feedback, fix only the root cause: materialize the lazy
Where/Select roles query once with ToArray() instead of a custom helper,
and revert the array fast path in RolesAuthorizationRequirement.

Co-authored-by: Copilot <[email protected]>

Copy link
Copy Markdown
Member Author

@DeagleGross Agreed. I switched to .ToArray() only and reverted the RolesAuthorizationRequirement change in 5169696.

I ran 3 interleaved rounds on AuthorizeRolesBenchmark (mean ± error, allocations):

Method main previous PR .ToArray()
Roles (avg of 3) 274.4 ns, 768 B 255.1 ns, 712 B 262.1 ns, 744 B
RolesWithSpaces (avg of 3) 317.2 ns, 880 B 278.9 ns, 752 B 290.3 ns, 784 B

.ToArray() gets −4.5%/−8.5% time and −24 B/−96 B. The previous version's extra time gain is inside the error bars (±10–38 ns per round). Its only consistent extra is 32 B, which is the array enumerator. That allocation is still there on .NET 12 because AllowedRoles is enumerated through IEnumerable<string>, but it isn't worth extra hot-path code. Per-round numbers are in the PR description. I also dropped the non-array fallback test, since that path no longer changes.

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

@davidfowl davidfowl removed the agent:working An AI agent is actively working on this issue/PR label Nov 6, 2026
@davidfowl davidfowl added the agent:working An AI agent is actively working on this issue/PR label Nov 6, 2026 — with Copilot SWE Agent
@davidfowl davidfowl removed the agent:working An AI agent is actively working on this issue/PR label Nov 6, 2026
@DeagleGross
DeagleGross enabled auto-merge (squash) November 6, 2026 21:30
@DeagleGross
DeagleGross merged commit 86c0eb5 into main Nov 6, 2026
27 checks passed
@DeagleGross
DeagleGross deleted the perf/authz-roles branch November 6, 2026 22:11
@github-actions

github-actions Bot commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

✅ No documentation PR was created.

Confidence that documentation is needed: 3%

No docs needed: internal performance optimization with tests and benchmark, no public API or observable behavior change.

Documentation surfaces considered

  • Conceptual article: Not required — Internal perf refactor; no public API or behavior change.
  • Migration guidance: Not required — No upgrade action needed.
  • Breaking change: Not required — No compatibility impact; roles, order, and exceptions unchanged.

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — 3279afae Deployed Nov 6, 2026 by DeagleGross via conclusion #227
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