liveBook · Manning

AddPolicy

As explained in ASP.NET Core in Action, 3e

AddPolicy is an ASP.NET Core authorization configuration method that registers a named policy defined by a policy builder.

AddPolicy registers a named policy during ASP.NET Core configuration. For authorization, the policy name must match the name supplied to [Authorize], while a lambda defines the required claims or other conditions. section 24.3

Require a boarding-pass claim

builder.Services.AddAuthorizationBuilder().AddPolicy("CanEnterSecurity", policyBuilder => policyBuilder.RequireClaim("BoardingPassNumber")); Applying [Authorize("CanEnterSecurity")] to a Razor Page allows users whose claims include BoardingPassNumber. Supplying a specific value narrows the rule: RequireClaim("BoardingPassNumber", "A1234"). section 24.3

Complex policies combine requirements and handlers. Every requirement must be satisfied, and handlers contain the logic that determines whether a requirement succeeds. section 24.7

The same method name also defines named CORS policies inside AddCors. Those policies can be selected for endpoints with RequireCors or [EnableCors], so avoid confusing CORS configuration with authorization configuration. section 29.3.3

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains simple claim requirements with examples, then outlines custom requirements and handlers without implementing them.
Examples
Uses a boarding-pass claim, the CanEnterSecurity policy, a Razor Page, and an exact A1234 claim value.
What it assumes
Assumes basic ASP.NET Core configuration and authorization attributes while defining claims, policies, and simple requirements.
What you can do after
Apply it via AddAuthorizationBuilder and AddPolicy to register claim-based rules for protected ASP.NET Core endpoints.
How it connects
Connects claims-based authorization, Authorize attributes, authorization middleware, policy requirements, handlers, and CORS policies.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.