Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 41 ยท JS Interop and Auth

Policies, Roles and Claims in Blazor

Protect Blazor pages and UI with roles, claims and policy-based authorization, write custom requirements and handlers, and use resource-based checks for individual records.

Knowing that a user is signed in is the easy part. Real applications ask richer questions: "Is this person an editor?", "Do they have a paid plan?", "Are they over 18?", "Is this their document?". ASP.NET Core answers with three tools that Blazor reuses: roles, claims and policies. This lesson shows each one, then builds a policy engine so you can see how decisions are made.

As in the previous lesson, the Razor and Program.cs code is real and read-only. The runnable examples are stand-ins: the Microsoft.AspNetCore.Authorization package is not available in the runner, so we reimplement the small idea behind it (requirements and handlers) in plain C#. Names intentionally mirror the real API.

Roles

A role is a claim of type role. It is the simplest tool and fine for coarse groups such as Admin and Editor:

RAZOR
@page "/admin"
@attribute [Authorize(Roles = "Admin")]

<h1>Admin area</h1>
RAZOR
<AuthorizeView Roles="Admin,Editor">
    <p>You can edit posts.</p>
</AuthorizeView>

A comma means "any of these roles". To require all roles, stack attributes: two [Authorize(Roles = ...)] lines mean the user needs both. Roles work, but they tend to multiply (EditorEurope, EditorUsa...) and they describe who the person is, not what they may do.

Claims

A claim is any fact in the token or cookie: department=sales, plan=pro, birthdate=.... Claims let you express things roles cannot, and you can read them directly:

RAZOR
@code {
    [CascadingParameter] private Task<AuthenticationState> AuthState { get; set; } = default!;

    private bool isPro;

    protected override async Task OnInitializedAsync()
    {
        var user = (await AuthState).User;
        isPro = user.HasClaim("plan", "pro");
    }
}

Reading claims in many components gets repetitive, and the rules drift apart. Policies solve that.

Policies

A policy gives a rule a name. You define it once in Program.cs and refer to it by name everywhere:

C#
builder.Services.AddAuthorizationCore(options =>
{
    options.AddPolicy("ProOnly", p => p.RequireClaim("plan", "pro"));
    options.AddPolicy("EditorsInSales", p => p
        .RequireRole("Editor")
        .RequireClaim("department", "sales"));
    options.AddPolicy("Adults", p => p.RequireAssertion(ctx =>
        ctx.User.HasClaim(c => c.Type == "age" && int.TryParse(c.Value, out var age) && age >= 18)));
});
RAZOR
@page "/reports"
@attribute [Authorize(Policy = "ProOnly")]

<AuthorizeView Policy="EditorsInSales">
    <button>Publish sales report</button>
</AuthorizeView>

When the rule changes (say "pro" now includes the "team" plan), you edit one line instead of hunting through components.

Requirements and handlers

For logic that does not fit RequireClaim, you write a requirement (the question, plain data) and a handler (the code that answers it):

C#
public record MinimumAgeRequirement(int Age) : IAuthorizationRequirement;

public class MinimumAgeHandler : AuthorizationHandler<MinimumAgeRequirement>
{
    protected override Task HandleRequirementAsync(
        AuthorizationHandlerContext context, MinimumAgeRequirement requirement)
    {
        var birth = context.User.FindFirst("birthdate")?.Value;
        if (DateOnly.TryParse(birth, out var date) &&
            date.AddYears(requirement.Age) <= DateOnly.FromDateTime(DateTime.Today))
        {
            context.Succeed(requirement);
        }
        return Task.CompletedTask;
    }
}

builder.Services.AddSingleton<IAuthorizationHandler, MinimumAgeHandler>();

A policy succeeds only when every requirement succeeds, and a requirement succeeds when at least one of its handlers calls Succeed. A handler that does nothing simply abstains; calling Fail() forces a failure.

A policy engine you can run

This stand-in reproduces the evaluation rules with the same names (Requirement, Handler, Succeed).

C# Stand-in: requirements, handlers and policies

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: maria passes ProOnly, Adults and ProAdults; tom fails all of them because he is both on the free plan and under 18; ada is an admin but not pro, so ProAdults is denied even though she is an adult. That "all requirements must pass" rule is the heart of policies.

Resource-based authorization

Roles and policies decide about the user. Sometimes the decision depends on a specific thing: "an editor may change only their own posts". You inject IAuthorizationService and pass the resource:

RAZOR
@inject IAuthorizationService Authorization

@code {
    [CascadingParameter] private Task<AuthenticationState> AuthState { get; set; } = default!;

    private async Task Delete(Post post)
    {
        var user = (await AuthState).User;
        var result = await Authorization.AuthorizeAsync(user, post, "CanEditPost");
        if (!result.Succeeded)
        {
            error = "You can only delete your own posts.";
            return;
        }
        await Posts.DeleteAsync(post.Id);
    }
}

The handler receives the Post through context.Resource and compares post.AuthorId with the user's id claim. Only the server code that deletes data must make this check for real; the component version just gives friendly feedback.

C# Stand-in: a resource-based rule

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.

Fallback and default policies

You can make every page require a signed-in user unless it opts out with [AllowAnonymous], which is safer than remembering to protect each page:

C#
builder.Services.AddAuthorizationBuilder()
    .SetFallbackPolicy(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build());

Secure-by-default beats secure-by-remembering.

Common mistakes

  • Authorizing only in the UI. The API or server method must check too.
  • Putting [Authorize] on a child component and expecting it to hide content; use AuthorizeView.
  • Role explosion. If you have roles like EditorFrance, use a claim and a policy.
  • Stale claims. A claim in a cookie or token does not change until the user signs in again or the token refreshes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A policy has two requirements. When does it succeed?

    Every requirement must be satisfied; each requirement needs at least one handler to call Succeed.
  2. 2. What does [Authorize(Roles = "Admin,Editor")] mean?

    A comma separated list means any of the roles. Stack attributes to require all of them.
  3. 3. When do you use resource-based authorization?

    IAuthorizationService.AuthorizeAsync(user, resource, policy) lets the handler see the resource.
  4. 4. What is the benefit of a fallback policy?

    It makes the safe behavior the default.

Summary

  • Roles are coarse groups; claims are flexible facts; policies give rules a name.
  • Define policies in Program.cs and use [Authorize(Policy = "...")] or AuthorizeView Policy.
  • Custom requirements and handlers express rules like minimum age; all requirements must pass.
  • Use IAuthorizationService with a resource for per-record checks.
  • Enforce on the server, and prefer a fallback policy so new pages are protected by default.

Next: Blazor Hosting Models