liveBook · Manning

ClaimsPrincipal

As explained in Building Web APIs with ASP.NET Core

ClaimsPrincipal is a .NET identity object representing a user or caller through one or more claims-based identities.

ClaimsPrincipal is a .NET identity object representing the current user or caller through one or more claims-based identities. Authorization policies can inspect its claims, check their presence or values, and transform or convert those values for policy decisions. section 9.4.7

RequireAssertion exposes the current ClaimsPrincipal through AuthorizationHandlerContext, allowing an anonymous policy function to make custom authorization checks. More elaborate policy-based authorization can use requirements and authorization handlers. 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)));

A minimum-age policy reads a date-of-birth claim from ctx.User, parses its value, and checks whether the user is at least 18. section 9.4.7

How Building Web APIs with ASP.NET Core covers it

How deep it goes
Explains claim inspection and value transformation, but stops short of implementing custom requirements and authorization handlers.
Examples
Uses moderator and mobile-phone claims plus a date-of-birth claim to demonstrate policy checks.
What you can do after
Apply it via ASP.NET Core authorization policies to inspect claims and restrict controllers, actions, or Minimal API methods.
How it connects
Connects claims with policy-based authorization, RequireAssertion, AuthorizationHandlerContext, and the Authorize attribute.

Also explained in

Compare how 2 books explain ClaimsPrincipal →

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.