LESSON 7 OF 15

Role-Based and Claim-Based Authorization

Learn how to protect ASP.NET Core MVC and API endpoints with roles, claims, and policy-based authorization rules.

45 dk 110

Introduction

Earlier lessons covered user registration, login, Identity integration, and cookie authentication. This lesson focuses on deciding what an authenticated user is allowed to do inside the application. This process is called authorization.

Authentication verifies who the user is, while authorization decides whether that user may access a resource or perform an operation. ASP.NET Core supports authorization through roles, claims, and policies. Roles usually represent broad groups of users, claims carry more specific information about an individual, and policies turn one or more facts into an access rule. ([learn.microsoft.com](https://learn.microsoft.com/en-us/aspnet/core/security/authorization/introduction?view=aspnetcore-8.0&utm_source=openai))

Roles versus claims

A role represents a user's general responsibility or membership in the application. Examples include Administrator, Editor, and Customer. A user can belong to more than one role. In ASP.NET Core Identity, role services must be registered with AddRoles<IdentityRole>() before role-based checks can be used.

A claim represents an individual fact about a user. Examples include a department, employee number, subscription tier, or permission. Although roles may be transported as role claims, not every claim is a role. Roles are useful for group membership, while claims are more appropriate for user attributes and fine-grained permissions. ([learn.microsoft.com](https://learn.microsoft.com/en-us/aspnet/core/mvc/security/authorization/roles?view=aspnetcore-10.0&utm_source=openai))

StructureExampleSuitable use
RoleAdministratorAccess to an administration area
ClaimDepartment=FinanceDepartment-specific operations
PolicyCanApproveInvoicesA rule combining one or more conditions

Enabling role services

If Identity has already been added to the project, extend its registration to include roles:

builder.Services.AddDefaultIdentity<ApplicationUser>(options =>
{
    options.SignIn.RequireConfirmedAccount = false;
})
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();

The authorization services and middleware must also be added to the request pipeline. UseAuthentication establishes the current user identity, and UseAuthorization evaluates access rules against that identity. The order matters:

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapDefaultControllerRoute();

If the middleware is missing or placed incorrectly, a signed-in user may still receive an unexpected authorization failure. ([learn.microsoft.com](https://learn.microsoft.com/en-us/aspnet/core/security/authorization/claims?view=aspnetcore-10.0&utm_source=openai))

Direct role-based protection

To restrict an entire MVC controller to one or more roles, use the Roles property of the Authorize attribute:

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

[Authorize(Roles = "Administrator")]
public class AdminController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

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

The expression Roles = "Administrator,Support" allows a user who belongs to at least one of the listed roles. An attribute on an action is combined with an attribute on its controller, so review the resulting rule when using multiple authorization attributes.

Use AllowAnonymous for an action that must remain available to unauthenticated users:

[AllowAnonymous]
public IActionResult Login()
{
    return View();
}

The same approach works with API controllers:

[ApiController]
[Route("api/admin/orders")]
[Authorize(Roles = "Administrator")]
public class AdminOrdersController : ControllerBase
{
    [HttpDelete("{id:int}")]
    public IActionResult Delete(int id)
    {
        return NoContent();
    }
}

An unauthenticated request will normally result in 401 Unauthorized. An authenticated request from a user who lacks the required role normally results in 403 Forbidden.

Creating roles and assigning them to users

Roles can be seeded during application startup. The following method creates each role only when it does not already exist:

public static async Task SeedRolesAsync(IServiceProvider services)
{
    var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>();

    string[] roles = ["Administrator", "Support", "Customer"];

    foreach (var role in roles)
    {
        if (!await roleManager.RoleExistsAsync(role))
        {
            await roleManager.CreateAsync(new IdentityRole(role));
        }
    }
}

Assign a role with UserManager:

var user = await userManager.FindByEmailAsync("ayse@example.com");

if (user is not null && !await userManager.IsInRoleAsync(user, "Support"))
{
    await userManager.AddToRoleAsync(user, "Support");
}

Managing role names through constants reduces spelling mistakes and casing inconsistencies:

public static class AppRoles
{
    public const string Administrator = "Administrator";
    public const string Support = "Support";
    public const string Customer = "Customer";
}

Defining claim-based policies

Role checks are useful for broad access decisions, but claim-based policies provide more flexibility. Suppose only employees in the Finance department who have an invoice permission may approve invoices:

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("CanApproveInvoices", policy =>
    {
        policy.RequireAuthenticatedUser();
        policy.RequireClaim("Department", "Finance");
        policy.RequireClaim("Permission", "Invoices.Approve");
    });
});

This policy requires the user to be authenticated and to have both Department=Finance and Permission=Invoices.Approve. Requirements within the same policy are evaluated together.

Apply the policy to an MVC action:

[Authorize(Policy = "CanApproveInvoices")]
public IActionResult Approve(int id)
{
    return RedirectToAction("Details", new { id });
}

Minimal API endpoints can use RequireAuthorization:

app.MapPost("/api/invoices/{id:int}/approve", (int id) =>
{
    return Results.NoContent();
})
.RequireAuthorization("CanApproveInvoices");

A policy can also check only for the presence of a claim, without requiring a particular value:

options.AddPolicy("EmployeeOnly", policy =>
    policy.RequireClaim("EmployeeNumber"));

When checking values, use consistent casing and controlled value sets for claim types and values. Avoid treating arbitrary user-provided text as a trusted authorization decision. ([learn.microsoft.com](https://learn.microsoft.com/en-us/aspnet/core/security/authorization/claims?view=aspnetcore-10.0&utm_source=openai))

Adding claims to an Identity user

Use UserManager.AddClaimAsync to add claims managed by ASP.NET Core Identity:

var user = await userManager.FindByEmailAsync("ayse@example.com");

if (user is not null)
{
    var claims = await userManager.GetClaimsAsync(user);

    if (!claims.Any(c => c.Type == "Department"))
    {
        await userManager.AddClaimAsync(
            user,
            new Claim("Department", "Finance"));
    }

    if (!claims.Any(c => c.Type == "Permission" && c.Value == "Invoices.Approve"))
    {
        await userManager.AddClaimAsync(
            user,
            new Claim("Permission", "Invoices.Approve"));
    }
}

With cookie authentication, claims in an existing authentication session may not be refreshed immediately after a claim is added. The user may need to sign in again, or the application may need to implement a secure cookie refresh flow. Plan how role and claim changes become effective for active sessions.

User access scenarios

Any authenticated user

[Authorize]
public IActionResult Profile()
{
    return View();
}

This requires a valid authenticated identity but no specific role or claim.

Allowing multiple roles

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

Users in either the Administrator or Support role can access the action.

Requiring both a role and a claim

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("SupportReadOnly", policy =>
    {
        policy.RequireRole("Support");
        policy.RequireClaim("TicketAccess", "Read");
    });
});

This policy requires both Support membership and the matching claim. Being in the role alone is not enough.

Common mistakes

  • Forgetting AddRoles: Register AddRoles<IdentityRole> when using Identity roles.
  • Ordering middleware incorrectly: UseAuthorization must run after authentication has established the user.
  • Using inconsistent role names: Admin, admin, and Administrator should not be treated as interchangeable. Use shared constants.
  • Confusing UI visibility with security: Hiding a menu item is not authorization. Protect the controller or endpoint on the server.
  • Trusting client-supplied headers: Authorization decisions must come from a validated identity or trusted server-side data.
  • Creating a role for every individual operation: Excessive roles become difficult to manage. Use claims or policies for fine-grained permissions.
  • Ignoring 401 and 403: Client applications should handle unauthenticated and unauthorized responses differently.

Practice exercise

Create a support-ticket API and implement these rules:

  1. Seed the Administrator, Support, and Customer roles.
  2. Allow all authenticated users to call GET /api/tickets.
  3. Allow only Customer and Support users to call POST /api/tickets.
  4. Allow only Administrators to call DELETE /api/tickets/{id}.
  5. Create a ManageTickets policy for Support users who have the TicketAccess=Manage claim.
  6. Test anonymous, Customer, Support, and Administrator users with Swagger or Postman, and record the expected 200, 401, and 403 responses.

Conclusion

Role-Based Authorization provides readable access rules for broad user groups. Claim-Based Authorization evaluates more detailed facts such as department, permission, or subscription level. Combining both approaches through policies creates a maintainable authorization layer for MVC pages and API endpoints.

In a secure application, access control must be enforced on the server at the controller, action, or endpoint level, not only in the user interface. The next stage is to apply these concepts to REST APIs secured with JWT Bearer authentication, where roles and claims are transported through token claims.

Sources