liveBook · Manning

RequireAssertion

As explained in Building Web APIs with ASP.NET Core

RequireAssertion is an ASP.NET Core authorization-policy builder method that adds a requirement evaluated by a custom assertion function.

RequireAssertion adds a custom authorization requirement to a policy in Program.cs. An anonymous function receives AuthorizationHandlerContext, whose ClaimsPrincipal lets the policy inspect, transform, or convert claim values. section 9.4.7

Minimum-age policy

A MinAge18 policy can require a date-of-birth claim, parse its yyyyMMdd value, and compare it with the current date minus 18 years. Apply the policy with [Authorize(Policy = "MinAge18")]. section 9.4.7

options.AddPolicy("MinAge18", policy =>
       policy
           .RequireAssertion(ctx => 
               ctx.User.HasClaim(c => c.Type == ClaimTypes.DateOfBirth)
               && DateTime.ParseExact(
                   "yyyyMMdd", 
                   ctx.User.Claims.First(c => 
                          c.Type == ClaimTypes.DateOfBirth).Value, 
                   System.Globalization.CultureInfo.InvariantCulture) 
                   >= DateTime.Now.AddYears(-18)));

Inspect the complete RequireAssertion configuration for the MinAge18 policy, including claim lookup, parsing, and age comparison. section 9.4.7

How Building Web APIs with ASP.NET Core covers it

How deep it goes
Explains the assertion context and a complete age check, but stops short of implementing custom requirements and handlers.
Examples
Demonstrates a MinAge18 policy that parses a date-of-birth claim and protects endpoints with an authorization policy.
What you can do after
Apply it via ASP.NET Core authorization policies to express custom claim-based access checks.
How it connects
Connects policy-based authorization with claims, ClaimsPrincipal, RBAC, CBAC, PBAC, and the Authorize attribute.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building Web APIs with ASP.NET Core. The section links point to the parts of the book it draws on.