LESSON 8 OF 15

Policy-Based Authorization and Custom Requirements

Use custom authorization requirements and handlers to combine claims, roles and resource data for age, department, permission and ownership rules.

45 dk 115

Introduction

In the previous lesson, we used role-based and claim-based authorization to apply access rules to users. In real applications, however, authorization rarely consists only of questions such as “Is the user an Admin?” or “Does the user have a Department claim?” A report might be editable only by users in the Finance department who have a specific permission and either own the report or belong to a manager role. Another operation may require the user to satisfy a minimum-age rule.

This lesson introduces Policy-Based Authorization for modeling these rules. A policy contains one or more authorization requirements. A requirement represents the rule, while a handler evaluates that rule against the user’s claims, roles or the resource being accessed. ASP.NET Core uses the authorization result to allow or reject the request. ([learn.microsoft.com](https://learn.microsoft.com/en-us/aspnet/core/security/authorization/policies?view=aspnetcore-10.0&utm_source=openai))

The relationship between policies, requirements and handlers

Policy-based authorization has three main building blocks:

  • Policy: A named collection of rules applied to a controller action or endpoint.
  • Requirement: A single condition that must be satisfied. It usually implements IAuthorizationRequirement.
  • Handler: The component that evaluates the requirement and calls context.Succeed(requirement) when the rule passes.

When a policy contains multiple requirements, the default behavior is AND logic. Every requirement must succeed for the policy to succeed. A handler does not always need to call context.Fail(); if the requirement is not marked as successful, authorization can fail. Use Fail when an explicit failure must override other successful handlers. Do not depend on the order in which handlers execute. ([learn.microsoft.com](https://learn.microsoft.com/en-us/aspnet/core/security/authorization/policies?view=aspnetcore-10.0&utm_source=openai))

Example scenario: editing a report

Assume that a user must meet the following rules to edit a report:

  1. The user must be authenticated.
  2. The user must have the Reports.Edit permission.
  3. The user must belong to the Finance department.
  4. The user must own the report or belong to the ReportManagers role.

The first three rules can be evaluated using information stored in the user principal. The final rule depends on a report loaded from the database. We will therefore combine custom policy requirements with resource-based authorization.

Creating a custom requirement

First, create a requirement representing the ability of an owner or manager to edit a report:

using Microsoft.AspNetCore.Authorization;

public sealed class ReportEditRequirement : IAuthorizationRequirement
{
}

This requirement does not contain data. It simply tells the authorization system that a handler must answer the question, “Can this user edit this report?” If a requirement needs parameters, such as a minimum age, it can expose a read-only property such as MinimumAge.

Implementing a requirement handler

A handler can specify both the requirement and the resource type. The following example uses a Report object as the resource:

using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;

public sealed class Report
{
    public int Id { get; set; }
    public string Title { get; set; } = string.Empty;
    public string OwnerId { get; set; } = string.Empty;
}

public sealed class ReportEditHandler
    : AuthorizationHandler<ReportEditRequirement, Report>
{
    protected override Task HandleRequirementAsync(
        AuthorizationHandlerContext context,
        ReportEditRequirement requirement,
        Report report)
    {
        if (context.User.IsInRole("ReportManagers"))
        {
            context.Succeed(requirement);
            return Task.CompletedTask;
        }

        var userId = context.User.FindFirstValue(ClaimTypes.NameIdentifier);

        if (!string.IsNullOrWhiteSpace(userId) &&
            string.Equals(userId, report.OwnerId, StringComparison.Ordinal))
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
}

The handler checks only ownership or the manager role. Keeping department and permission checks in separate requirements makes each rule easier to reuse and test independently.

A custom claim-based requirement

Assume that the Reports.Edit permission is stored as a claim. Claim types can be centralized as application constants:

public static class AppClaimTypes
{
    public const string Permission = "permission";
    public const string Department = "department";
}

The permission requirement can be implemented as follows:

public sealed class PermissionRequirement(string permission)
    : IAuthorizationRequirement
{
    public string Permission { get; } = permission;
}

public sealed class PermissionHandler
    : AuthorizationHandler<PermissionRequirement>
{
    protected override Task HandleRequirementAsync(
        AuthorizationHandlerContext context,
        PermissionRequirement requirement)
    {
        var hasPermission = context.User
            .FindAll(AppClaimTypes.Permission)
            .Any(c => string.Equals(
                c.Value,
                requirement.Permission,
                StringComparison.OrdinalIgnoreCase));

        if (hasPermission)
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
}

This check assumes that the user’s JWT or cookie principal was created with the correct permission claims. Authorization should not trust a form field or an unrelated HTTP header supplied by the client. Permission data must be part of a trusted authentication process.

A department requirement

public sealed class DepartmentRequirement(string department)
    : IAuthorizationRequirement
{
    public string Department { get; } = department;
}

public sealed class DepartmentHandler
    : AuthorizationHandler<DepartmentRequirement>
{
    protected override Task HandleRequirementAsync(
        AuthorizationHandlerContext context,
        DepartmentRequirement requirement)
    {
        var department = context.User.FindFirst(AppClaimTypes.Department)?.Value;

        if (string.Equals(
            department,
            requirement.Department,
            StringComparison.OrdinalIgnoreCase))
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
}

If the claim is missing or does not match the expected value, the handler does not report success. In sensitive systems, also consider how long changing information such as a department should remain inside a token. If a user changes departments, an old access token may continue to contain the previous value until it expires.

Registering policies in Program.cs

Register the handlers with dependency injection and add the policy:

using Microsoft.AspNetCore.Authorization;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddAuthentication();

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("EditCompanyReport", policy =>
    {
        policy.RequireAuthenticatedUser();
        policy.Requirements.Add(
            new PermissionRequirement("Reports.Edit"));
        policy.Requirements.Add(
            new DepartmentRequirement("Finance"));
        policy.Requirements.Add(new ReportEditRequirement());
    });
});

builder.Services.AddSingleton<IAuthorizationHandler, PermissionHandler>();
builder.Services.AddSingleton<IAuthorizationHandler, DepartmentHandler>();
builder.Services.AddSingleton<IAuthorizationHandler, ReportEditHandler>();

Because three requirements are registered in the same policy, all three must succeed. Since ReportEditRequirement needs a resource, we will pass the report object when calling the authorization service.

Protecting an action with resource-based authorization

When the ownership information is not known until a record is loaded, applying only [Authorize(Policy = "EditCompanyReport")] may not be sufficient. The attribute can run before the report is loaded from the database. In that situation, load the resource first and then call IAuthorizationService.AuthorizeAsync. ([learn.microsoft.com](https://learn.microsoft.com/en-us/aspnet/core/security/authorization/resource-based?view=aspnetcore-10.0&utm_source=openai))

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/reports")]
public sealed class ReportsController(
    IAuthorizationService authorizationService,
    IReportRepository repository) : ControllerBase
{
    [HttpPut("{id:int}")]
    public async Task<IActionResult> Update(
        int id,
        UpdateReportRequest request)
    {
        var report = await repository.FindAsync(id);

        if (report is null)
        {
            return NotFound();
        }

        var result = await authorizationService.AuthorizeAsync(
            User,
            report,
            "EditCompanyReport");

        if (!result.Succeeded)
        {
            return Forbid();
        }

        report.Title = request.Title;
        await repository.SaveAsync(report);

        return NoContent();
    }
}

public sealed record UpdateReportRequest(string Title);

The AuthorizeAsync call receives the current user, the resource and the policy name. An unauthenticated request normally results in a challenge, while an authenticated user without sufficient permissions receives a forbid result. APIs should expose these outcomes consistently to clients.

Calculated rules such as minimum age

When authorization requires calculating an age from a birth-date claim, a custom handler is more appropriate than a simple claim-presence check:

public sealed class MinimumAgeRequirement(int minimumAge)
    : IAuthorizationRequirement
{
    public int MinimumAge { get; } = minimumAge;
}

public sealed class MinimumAgeHandler
    : AuthorizationHandler<MinimumAgeRequirement>
{
    protected override Task HandleRequirementAsync(
        AuthorizationHandlerContext context,
        MinimumAgeRequirement requirement)
    {
        var value = context.User.FindFirstValue("birthdate");

        if (!DateOnly.TryParse(value, out var birthDate))
        {
            return Task.CompletedTask;
        }

        var today = DateOnly.FromDateTime(DateTime.UtcNow);
        var age = today.Year - birthDate.Year;

        if (birthDate > today.AddYears(-age))
        {
            age--;
        }

        if (age >= requirement.MinimumAge)
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
}

Register the policy with new MinimumAgeRequirement(21). Use a consistent date format across token issuers, and reject access when the birth date is missing or invalid. If claims contain personal data, avoid writing their values to application logs.

Applying a policy to an endpoint

An MVC action can specify a policy with the Authorize attribute:

[Authorize(Policy = "EditCompanyReport")]
[HttpPost("{id:int}/publish")]
public async Task<IActionResult> Publish(int id)
{
    // Resource loading and imperative authorization can happen here.
    return Ok();
}

However, if the action makes a decision about the resource owner, the attribute should be used for authentication or general access rules while the resource-specific decision is performed separately. In Minimal APIs, use .RequireAuthorization("EditCompanyReport"); the resource-specific check still belongs in the endpoint or application service.

Common mistakes

  • Using the wrong policy name: The name in the attribute must exactly match the name passed to AddPolicy.
  • Forgetting handler registration: A requirement without a registered handler cannot normally succeed.
  • Mixing role and claim types: Ensure that the role claim in the JWT matches the configured RoleClaimType.
  • Trusting client data: A body field such as isOwner=true must never determine authorization.
  • Checking ownership before loading the resource: A user identifier in the URL does not prove ownership of the database record.
  • Accidentally creating AND logic: Adding two requirements does not express “Admin or Owner.” Model alternatives in one handler or use an appropriate assertion.
  • Depending on handler order: Handlers may run in any order and should not rely on side effects from another handler.
  • Using overly broad roles: Assigning every operation to the Admin role reduces the value of a fine-grained permission model.

Short practice exercise

Create a ViewContract policy for a customer-contract endpoint. The policy must require:

  1. An authenticated user.
  2. The Contracts.Read permission.
  3. Either the user’s department must match the contract’s department, or the user must belong to the ContractAuditors role.

Use at least one custom requirement and handler. After loading the contract from the database, call IAuthorizationService.AuthorizeAsync(User, contract, "ViewContract"). Prepare at least three test cases: a missing permission claim, a user from another department, and an authorized auditor.

Conclusion

Policy-Based Authorization separates authorization rules from controller and endpoint code, making them more readable, reusable and testable. Claim and role checks can evaluate the user principal, while ownership and similar resource decisions should be made after the real resource has been loaded through imperative authorization.

A maintainable design uses meaningful policy names, small single-purpose requirements and handlers that obtain data from trusted sources. In the next stage, this approach can be applied to JWT-protected APIs to see how token claims participate in policy evaluation.

Sources