Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 52 ยท Authentication and Authorization

Authorization: Roles, Policies and Handlers

Learn ASP.NET Core authorization: roles, claim-based policies, custom requirements and handlers, resource-based checks and a fallback policy, with live examples.

Authentication tells your app who is calling. Authorization decides what that caller may do. ASP.NET Core gives you a layered model for it: simple role checks for easy cases, named policies for rules you want to reuse, requirements and handlers for rules that need code, and resource-based checks for rules that depend on the specific object being accessed ("only the author may edit this post").

In this lesson you will work through each layer with running examples. Every program uses a tiny header-based authentication scheme (like the API key handler from Authentication Concepts) so you can change who is calling just by changing request headers.

The pieces and how they fit

flowchart LR
    E["Endpoint<br/>RequireAuthorization(...)"] --> P["Policy"]
    P --> R1["Requirement 1"]
    P --> R2["Requirement 2"]
    R1 --> H1["Handler(s)"]
    R2 --> H2["Handler(s)"]
    H1 --> D{"All requirements<br/>succeeded?"}
    H2 --> D
    D -- "Yes" --> OK["Allowed"]
    D -- "No, signed in" --> F["Forbid (403)"]
    D -- "No, anonymous" --> C["Challenge (401)"]

A policy is a list of requirements; each requirement is checked by one or more handlers. All requirements must succeed.

Vocabulary to keep straight:

  • A requirement is a data class that says what must be true (MinimumAge(18)).
  • A handler is the code that decides whether the current user meets it.
  • A policy bundles requirements under a name.
  • Roles, claim checks and "must be authenticated" are all just built-in requirements.

As the previous lesson showed, a caller who is not signed in gets a challenge (401) and a signed-in caller who fails the policy gets a forbid (403).

Requiring a login, roles and claims

The simplest rule is "must be signed in": RequireAuthorization() on an endpoint (or [Authorize] on a controller). You add detail by naming a role or a policy.

  • RequireRole("admin", "editor") inside a policy builder means admin or editor.
  • Calling RequireAuthorization several times stacks policies, and all of them must pass, so two separate role calls mean admin and editor.
  • RequireClaim("plan", "pro", "enterprise") demands a claim of that type with one of those values.

A fallback policy applies to every endpoint that has no authorization metadata at all, and it is the safest default: new endpoints are locked down until someone consciously opens them with AllowAnonymous(). A related setting, the default policy, is what a bare RequireAuthorization() or [Authorize] uses.

C# Roles, claim policies and a fallback policy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Read the table. /dashboard has no attributes at all, yet it still demands a login thanks to the fallback policy, while / opted out explicitly. A free-plan user is forbidden from /reports (403) though signed in, and an anonymous caller would get a 401 instead. Last, notice how one RequireRole("admin", "editor") call is an OR but two stacked calls are an AND.

In controllers the same ideas use attributes. [Authorize(Roles = "admin,editor")] is OR; two attributes, [Authorize(Roles = "admin")] plus [Authorize(Roles = "editor")], are AND. [Authorize(Policy = "PremiumOnly")] names a policy and [AllowAnonymous] opts out. See Controllers and Actions.

Custom requirements and handlers

Roles and claim values cover plenty, but real rules look like "must be 18 or older", "must have worked here for a year" or "must be inside business hours". For those you write a requirement and a handler.

A requirement implements the marker interface IAuthorizationRequirement and carries the parameters of the rule. A handler derives from AuthorizationHandler<TRequirement> and calls context.Succeed(requirement) when the user qualifies. Understand the three possible outcomes of a handler:

  • Succeed: this handler is satisfied.
  • Do nothing (return without calling anything): this handler has no opinion. The requirement fails only if no handler succeeds.
  • Fail: calling context.Fail() makes the whole requirement fail no matter what other handlers say. Use it rarely, for hard "never allow" rules.

Because the default is "do nothing", several handlers for one requirement behave as OR. That is a handy way to add an exception such as "staff always qualify".

Handlers are registered in dependency injection as IAuthorizationHandler, so they can take services in their constructors. A singleton is fine when the handler is stateless.

C# A minimum-age requirement with two handlers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The staff member has no age claim at all, so MinimumAgeHandler does nothing, but StaffBypassHandler succeeds and the requirement is met. IAuthorizationService.AuthorizeAsync is the same engine the middleware uses, available to your own code, and its result tells you which requirements failed.

If a requirement needs no per-handler logic you can skip the separate handler class: a requirement may implement IAuthorizationHandler itself, and a policy can use RequireAssertion(context => ...) for one-off lambdas.

Resource-based authorization

Some rules cannot be decided from the user alone. "Can this user edit this document?" needs the document. Policies attached to endpoints run before your handler loads anything, so they have no resource to look at. Instead you load the object yourself and ask IAuthorizationService:

C#
Document? doc = store.Find(id);
if (doc is null) return Results.NotFound();

AuthorizationResult result = await authorization.AuthorizeAsync(user, doc, Operations.Edit);
if (!result.Succeeded) return Results.Forbid();

The handler derives from AuthorizationHandler<TRequirement, TResource>. A convenient built-in requirement type is OperationAuthorizationRequirement, a named operation such as Read or Edit, so one handler can rule on all operations for a resource type.

C# Only owners can edit; published documents are public

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice the order inside the endpoint: look up the resource, return 404 if it does not exist, and only then authorize. For documents that are sensitive you may even prefer 404 for "exists but not yours", so the endpoint does not confirm that an id exists. That is a policy decision about information leaks, not a framework rule.

Do not scatter if (user.Name == doc.Owner) checks through your handlers. Centralizing the rule in one authorization handler means a new endpoint (export, delete, share) only has to ask the question, and the answer is the same everywhere.

Choosing the right tool

Situation Use
"Must be signed in" RequireAuthorization() or [Authorize]
A few fixed groups of people Roles
A reusable rule over claims A named policy with RequireClaim / RequireAssertion
A rule needing code or services A requirement and a handler
A rule depending on the specific object Resource-based authorization with IAuthorizationService
"Lock everything unless opened" Fallback policy + AllowAnonymous

Authorization decides what the application allows. It is also worth securing the transport and the inputs, which Web Security Essentials covers, and ASP.NET Core Identity Overview explains the framework that stores users and roles for you.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. An endpoint has .RequireAuthorization(p => p.RequireRole("admin")).RequireAuthorization(p => p.RequireRole("editor")). Who may call it?

    Stacked authorization calls (or two [Authorize] attributes) are combined with AND. A single RequireRole("admin", "editor") would be an OR.
  2. 2. Two handlers exist for the same requirement; one succeeds and the other returns without doing anything. What is the result?

    A handler that neither succeeds nor fails has no opinion. The requirement is met if at least one handler succeeds, unless some handler explicitly calls Fail().
  3. 3. What does a fallback policy do?

    The fallback policy covers endpoints without [Authorize]/[AllowAnonymous] metadata. With RequireAuthenticatedUser it makes every new endpoint private until you call AllowAnonymous.
  4. 4. Why is a rule like "only the author may edit this post" implemented with IAuthorizationService and a resource?

    Endpoint-level policies are evaluated before your code loads the entity. For decisions that depend on a specific object, load it first and pass it to AuthorizeAsync.
  5. 5. A signed-in user fails a policy. Which response does the framework produce?

    Known caller, insufficient permission: forbid, which cookie schemes turn into a redirect to an access-denied page and API schemes into 403.

Summary

  • Authorization asks what a known caller may do; failure produces 401 (anonymous) or 403 (signed in).
  • Roles and RequireClaim handle simple cases; one RequireRole call with several roles is OR, stacked calls are AND.
  • A policy is a named list of requirements; handlers decide each requirement, and several handlers for one requirement act as OR.
  • Use context.Succeed to approve, do nothing for "no opinion", and Fail only for hard denials.
  • Resource-based checks call IAuthorizationService.AuthorizeAsync(user, resource, requirement) after loading the object.
  • A fallback policy with RequireAuthenticatedUser plus AllowAnonymous makes endpoints private by default.

Next: ASP.NET Core Identity Overview