Archive for May, 2025|Monthly archive page

Understanding Role-Based, Policy-Based, and Imperative Checks in ASP.Net Core

3 Types:

  1. Role
  2. Policy-Based
  3. Imperative checks

Role

General, top-level, overarching user attribute. Like a job title such as Administrator, Librarian, Student, User.

Role-based authorization is saying: If the user is an Administrator, allows them access to the user management page. It is a simple, role-based authorization.

[Authorize(Roles = "Administrator")]
public IActionResult ManageUsers()
{
    return View();
}

Policy-based

Use a set of user claims to fine tune authorization, for consistent enforcement across multiple controllers or actions. Otherwise, check one or two user claims in a specific place.

Think of claims as subordinate, sub attributes of a user. For example, Department: Accounting, Region: Northwest, Degree: PhD.

Say you want to allow access to certain resources to users by the region they are in. You may have a policy called InNorthwestRegion where the claim is Region = Northwest.

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("InNorthwestRegion", policy =>
        policy.RequireClaim("Region", "Northwest"));
});

Then, enforce this policy:

[Authorize(Policy = "InNorthwestRegion")]
public IActionResult EditReport()
{
    return View();
}

That is a lot cleaner than having to check user claims consistently across multiple controllers:

if (User.HasClaim(c => c.Type == "Region" && c.Value == "Northwest"))
{
    // User has the claim, allow access
}
else
{
    return Forbid();
}

You can combine roles with policies. For example, only Administrators in the Northwest Region can manage this server. In this case Role = Administrator, Policy = InNorthwestRegion.

[Authorize(Roles = "Administrator")]
[Authorize(Policy = "InNorthwestRegion")]
public IActionResult EditReport()
{
    return View();
}

Imperative Check

Used when authorization logic requires more dynamic evaluation. Can be performed using IAuthorizationService, allowing developers to evaluate both user identity and resource properties before granting access.

An example of this could be checking if a user has ownership rights to a specific document before allowing edits.