Policies and resource authorization
Policies and resource authorization
An authorization policy is a named group of requirements. The authorization service evaluates those requirements against a principal and, when needed, a resource. Endpoint-level roles are useful for broad permissions; ownership and tenant isolation require a check against the actual record being requested.
For a claim policy, use RequireAuthenticatedUser with RequireClaim or RequireRole. Multiple requirements in one policy must succeed; multiple permitted values inside one RequireClaim or RequireRole call can represent alternatives. A resource handler receives the resource object; call IAuthorizationService.AuthorizeAsync after loading it within the trusted server boundary. Check an immutable, verified subject identifier rather than a display name. When multiple schemes or identities are present, explicitly define which trusted identity and issuer supply the subject and tenant claims. Do not combine unrelated identities or silently accept ambiguous duplicate values. A narrow single-identity policy can reject ambiguity; other applications need a documented scheme-specific policy. Claim issuer strings alone do not validate tokens. A hard denial via context.Fail cannot be overridden by another handler; leaving a requirement unsatisfied is different. For multitenant systems include tenant as well as subject, or constrain the database query by both. Deny missing claims, unknown resources and unexpected states. A route parameter or submitted owner ID is not a permission claim. Never rely on disabled buttons or client checks. An HTTP endpoint can challenge unauthenticated callers and forbid authenticated failures; some applications deliberately return 404 for unauthorized resource access to limit enumeration, consistently and with appropriate logging. A direct authorization test proves the policy decision only, not the full HTTP pipeline or database filtering.
Baseline: .NET 10 / C# 14 with Microsoft.AspNetCore.App shared framework. All snippets are independent console fixtures, not ByteMind runner code. In an approved isolated environment with a reviewed installed SDK and targeting packs, use dotnet build and dotnet run --no-build in the fixture directory; restore only from approved sources if required. No external service, real user data, account or credential is needed. Expected results are reasoned, not executed; cryptographic random data is not printed.
Require both a role and an authenticated identity
A named policy needs a verified identity and an editor role. Synthetic principals are supplied directly, without accepting external claims.
using System.Security.Claims;using Microsoft.AspNetCore.Authorization;using Microsoft.Extensions.DependencyInjection;var services = new ServiceCollection();services.AddLogging();services.AddAuthorizationCore(o => o.AddPolicy("Edit", p => p.RequireAuthenticatedUser().RequireRole("Editor")));using var sp = services.BuildServiceProvider();var auth = sp.GetRequiredService<IAuthorizationService>();foreach (var (role, scheme) in new[] { ("Editor", "fixture"), ("Reader", "fixture"), ("Editor", "") }) { var user = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Role, role) }, scheme)); Console.WriteLine((await auth.AuthorizeAsync(user, null, "Edit")).Succeeded);}Expected output (not executed):
TrueFalseFalseAn unauthenticated identity with a role-shaped claim is denied because both requirements must pass.
Check ownership and tenant in a resource handler
A stored document carries the trusted owner and tenant. The handler succeeds only if both claims match and the test identity is authenticated.
using System.Security.Claims;using Microsoft.AspNetCore.Authorization;using Microsoft.Extensions.DependencyInjection;var services = new ServiceCollection();services.AddLogging();services.AddAuthorizationCore(o => o.AddPolicy("ReadOwn", p => p.RequireAuthenticatedUser().AddRequirements(new OwnDocument())));services.AddSingleton<IAuthorizationHandler, OwnDocumentHandler>();using var sp = services.BuildServiceProvider();var auth = sp.GetRequiredService<IAuthorizationService>();var doc = new Document("north", "u1");foreach (var (tenant, subject) in new[] { ("north", "u1"), ("north", "u2"), ("south", "u1") }) { var user = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim("tenant", tenant), new Claim(ClaimTypes.NameIdentifier, subject) }, "fixture")); Console.WriteLine((await auth.AuthorizeAsync(user, doc, "ReadOwn")).Succeeded);}record Document(string Tenant, string Owner);sealed class OwnDocument : IAuthorizationRequirement { }sealed class OwnDocumentHandler : AuthorizationHandler<OwnDocument, Document> { protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, OwnDocument requirement, Document resource) { if (context.User.Identity?.IsAuthenticated == true && context.User.FindFirst("tenant")?.Value == resource.Tenant && context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value == resource.Owner) context.Succeed(requirement); return Task.CompletedTask; }}Expected output (not executed):
TrueFalseFalseThe same subject in a different tenant is denied. The example assumes one trusted identity; a production app must validate its issuer and claim mapping before evaluation.
Apply a claim policy with two requirements
A review policy requires both a department and a permission. Missing or unrelated claims fail closed.
using System.Security.Claims;using Microsoft.AspNetCore.Authorization;using Microsoft.Extensions.DependencyInjection;var services = new ServiceCollection();services.AddLogging();services.AddAuthorizationCore(o => o.AddPolicy("Review", p => p.RequireAuthenticatedUser().RequireClaim("department", "catalog", "support").RequireClaim("permission", "review")));using var sp = services.BuildServiceProvider();var auth = sp.GetRequiredService<IAuthorizationService>();foreach (var (department, permission) in new[] { ("support", "review"), ("catalog", "read"), ("billing", "review") }) { var user = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim("department", department), new Claim("permission", permission) }, "fixture")); Console.WriteLine((await auth.AuthorizeAsync(user, null, "Review")).Succeeded);}Expected output (not executed):
TrueFalseFalseThe department may match either approved value, but the permission requirement still must pass.
Apply the concept
Extend ReadOwn to allow a verified document owner to read a document only when it is not archived. Describe the cases for a missing tenant, another owner, same owner in another tenant, and an archived document.
Use the manual practice and knowledge check to reason about the boundary. Do not deploy these fixtures as production security controls.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Policies and resource authorization — knowledge check
Apply the lesson concepts to the following scenarios.
A user owns record 7 but requests record 8. Which check is essential?
Two requirements are added to one policy. How do they normally combine?
Why compare tenant as well as subject?
A claim is absent. What should the example ownership handler do?
What does a successful direct AuthorizeAsync test establish?