Repository navigation
Materialize trimmed [Authorize] roles once in AuthorizationPolicy.CombineAsync - #70183
Conversation
…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]>
There was a problem hiding this comment.
🟢 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
|
/review |
Co-authored-by: Copilot <[email protected]>
|
The root cause is that the lazy 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 I'd also drop all changes from |
…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]>
|
@DeagleGross Agreed. I switched to I ran 3 interleaved rounds on
🤖 Posted by ASP.NET Core Perf 2 (AI Agent) |
Co-authored-by: Copilot <[email protected]>
|
✅ 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
|
Materialize trimmed [Authorize] roles once in AuthorizationPolicy.CombineAsync
Stop re-running the lazy
[Authorize(Roles = ...)]query on every request.Description
AuthorizationPolicy.CombineAsyncpassed a lazyWhere/Selectquery toRequireRole, andRolesAuthorizationRequirementstored it asAllowedRoles. The combined policy is cached per endpoint (AuthorizationPolicyCacheinAuthorizationMiddleware, and MVC'sAuthorizeFilter), so every authorization check re-ran the query. Each run allocated the iterator, re-ranIsNullOrWhiteSpaceand calledTrim()again, which allocates a new string for every role with surrounding spaces. End-to-end profiling with dotnet-trace showed thisArrayWhereSelectIterator<string, string>on every request.The fix materializes the query once with
.ToArray()when the policy is built. Roles, order, whitespace-entry skipping and theInvalidOperationExceptionfor an all-whitespaceRolesare unchanged. There are no public API changes.Tests:
AuthorizationPolicyFacts.CombineTrimsRolesOnceAndPreservesOrderchecks order and trimming, and that repeated enumeration returns the same string instances. It fails on main.AuthorizationPolicyFacts.CombineThrowsForRolesWithOnlyWhitespaceEntriespins the existing exception behavior.Microsoft.AspNetCore.Authorization.Test: 169/169 passed.Benchmark
src/Security/perf/Microbenchmarks/AuthorizeRolesBenchmark.csbuilds policies once withCombineAsyncfrom[Authorize(Roles = "Admin,User")]and[Authorize(Roles = "Manager, Editor, User")], then callsIAuthorizationService.AuthorizeAsyncfor a user in roleUser. "main" is the merge base 4f556f7. "Earlier PR" is the previous revision of this PR (9dd2ee5: custom trim helper plus astring[]fast path inRolesAuthorizationRequirement). "This PR" is.ToArray()only. Runs were interleaved (main, earlier PR, this PR) ×3..ToArray())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)