ASP.NET Core MVC Advanced

Role-based authorization

Roles group users by job, such as Admin, Manager or Customer, and let you allow whole groups into parts of the app. This lesson shows how to create roles with Identity, assign users to them and protect actions by role.

How a role check works
  1. StartRoles existAdmin and Manager are created with RoleManager
  2. Step 2User is assignedUserManager.AddToRoleAsync(user, "Manager")
  3. Step 3User signs inTheir roles are added to the cookie as role claims
  4. Step 4Protected action[Authorize(Roles = "Admin,Manager")]
  5. EndClaims checkedHas the Admin or Manager role? Allowed, otherwise 403

The idea in plain words

A role is a named group. With Identity, roles are stored in the AspNetRoles table and linked to users. When a user signs in, their roles become role claims in the authentication cookie, so checks are fast and need no database call.

In [Authorize(Roles = "Admin,Manager")] the comma means OR: either role is enough. Stacking two [Authorize] attributes with different roles means AND: the user needs both.

Example: create roles and assign a user

Enable roles with AddRoles<IdentityRole>(), then seed them at startup.

C#
using (var scope = app.Services.CreateScope())
{
    var roles = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
    foreach (var name in new[] { "Admin", "Manager" })
        if (!await roles.RoleExistsAsync(name))
            await roles.CreateAsync(new IdentityRole(name));

    var users = scope.ServiceProvider.GetRequiredService<UserManager<IdentityUser>>();
    var admin = await users.FindByEmailAsync("[email protected]");
    if (admin is not null && !await users.IsInRoleAsync(admin, "Admin"))
        await users.AddToRoleAsync(admin, "Admin");
}

Example: protect actions and views

Razor
[Authorize(Roles = "Admin,Manager")]      // Admin OR Manager
public class ReportsController : Controller
{
    public IActionResult Sales() => View();

    [Authorize(Roles = "Admin")]           // only Admin for this one
    public IActionResult Payroll() => View();
}

@* In a view: show the link only to admins *@
@if (User.IsInRole("Admin"))
{
    <a asp-controller="Reports" asp-action="Payroll">Payroll</a>
}

Common mistakes

  • Expecting a role change to apply immediately; the user's cookie still has the old roles until they sign in again or the security stamp is refreshed.
  • Creating a role for every small permission. When rules get detailed, use policies and claims.
  • Spelling role names differently in different places; keep them in constants.

Interview question

How do you require a user to have two roles at once in ASP.NET Core?

Apply two separate [Authorize] attributes, such as [Authorize(Roles = "Admin")] and [Authorize(Roles = "Finance")], on the controller or action; every attribute must be satisfied. A single attribute with a comma-separated list, Roles = "Admin,Finance", only requires one of them. A policy built with RequireRole for each role also works.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.