Introduction
In the previous lesson, we implemented user authentication and administrator login. However, the fact that a user can sign in does not mean that the user should be allowed to perform every operation. For example, an editor may create and update articles, while only an administrator should manage users, roles, or site settings. This distinction is provided by authorization.
In this lesson, we will define two roles for our content management application: Admin and Editor. We will then restrict the administration area, apply role-based checks, and use policy-based authorization for more expressive business rules. We will also see why authorization is not simply a matter of hiding menu items: Controller and action endpoints must enforce the rules on the server.
Authentication versus authorization
Authentication determines who the user is. After a successful login through a password, cookie, or another identity provider, ASP.NET Core creates the authenticated principal represented by HttpContext.User.
Authorization determines what that user is allowed to access or do. An authenticated user may still be denied access to a Controller, action, resource, or specific operation. ASP.NET Core MVC supports authorization based on roles, claims, and policies.
Hiding a button is not a security control. A user can still call the URL or send an HTTP request directly, so the Controller must perform the authorization check.
Defining application roles
Instead of repeating role names as string literals throughout the application, keep them in a single constants class. This reduces spelling mistakes and makes future changes easier.
namespace CmsApp.Security;
public static class AppRoles
{
public const string Admin = "Admin";
public const string Editor = "Editor";
}Identity must be configured with AddRoles<IdentityRole> before role-based authorization can be used. If the previous lesson configured Identity with AddDefaultIdentity, extend the existing service registration as follows.
using Microsoft.AspNetCore.Identity;
builder.Services
.AddDefaultIdentity<ApplicationUser>(options =>
{
options.SignIn.RequireConfirmedAccount = false;
})
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();If you configured Identity manually with AddIdentityCore, the equivalent setup is:
builder.Services
.AddIdentityCore<ApplicationUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddSignInManager();Creating roles in the database
Creating the role definitions does not automatically assign them to users. A startup seed operation can create the roles safely and avoid duplicates by checking whether each role already exists.
using Microsoft.AspNetCore.Identity;
using CmsApp.Security;
namespace CmsApp.Data;
public static class IdentitySeed
{
public static async Task SeedRolesAsync(IServiceProvider services)
{
var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>();
foreach (var roleName in new[] { AppRoles.Admin, AppRoles.Editor })
{
if (!await roleManager.RoleExistsAsync(roleName))
{
var result = await roleManager.CreateAsync(new IdentityRole(roleName));
if (!result.Succeeded)
{
var errors = string.Join(", ", result.Errors.Select(e => e.Description));
throw new InvalidOperationException($"Role creation failed: {errors}");
}
}
}
}
}Call the seed method from Program.cs inside a service scope after building the application.
using CmsApp.Data;
var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
await IdentitySeed.SeedRolesAsync(scope.ServiceProvider);
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "areas",
pattern: "{area:exists}/{controller=Dashboard}/{action=Index}/{id?}");
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();When using migrations, make sure the Identity tables exist in the database. Role definitions are stored in AspNetRoles, while user-role relationships are stored in AspNetUserRoles.
Assigning a role to a user
After creating roles, assign them to users through UserManager<ApplicationUser>. The following example creates an initial administrator if one does not already exist.
public static async Task SeedAdminAsync(IServiceProvider services)
{
var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
var adminEmail = "admin@example.com";
var admin = await userManager.FindByEmailAsync(adminEmail);
if (admin is null)
{
admin = new ApplicationUser
{
UserName = adminEmail,
Email = adminEmail,
EmailConfirmed = true
};
var createResult = await userManager.CreateAsync(admin, "ChangeThisPassword_123!");
if (!createResult.Succeeded)
{
var errors = string.Join(", ", createResult.Errors.Select(e => e.Description));
throw new InvalidOperationException($"Admin creation failed: {errors}");
}
}
if (!await userManager.IsInRoleAsync(admin, AppRoles.Admin))
{
await userManager.AddToRoleAsync(admin, AppRoles.Admin);
}
}Never keep an initial password in source code in a production application. Use a secret store, environment variable, or first-run setup process. Requiring the initial administrator to change the password after the first login is also a useful safeguard.
Protecting the administration area
Placing administration controllers inside an MVC Area provides a clean route and file structure. For example, the controller can be located at Areas/Admin/Controllers/DashboardController.cs.
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using CmsApp.Security;
namespace CmsApp.Areas.Admin.Controllers;
[Area("Admin")]
[Authorize(Roles = AppRoles.Admin + "," + AppRoles.Editor)]
public class DashboardController : Controller
{
public IActionResult Index()
{
return View();
}
}In [Authorize(Roles = "Admin,Editor")], the comma means that membership in either role is sufficient. If an operation truly requires both roles, multiple authorization declarations can be combined, but the usual administration-panel requirement is “Admin or Editor.”
For administrator-only operations, apply a narrower rule to an action or Controller.
[Area("Admin")]
[Authorize(Roles = AppRoles.Admin)]
public class UsersController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Disable(string id)
{
// Disable the selected user.
return RedirectToAction(nameof(Index));
}
}The Editor can manage content but cannot open user-management actions. This restriction is applied to the endpoint itself, not only to the navigation menu.
Policy-based authorization
Roles are clear and useful for simple rules. More detailed requirements may appear later, such as “the user must be an Editor and have a confirmed account” or “the user must have permission to publish content.” Named policies make these rules centralized, readable, and easier to extend.
using Microsoft.AspNetCore.Authorization;
using CmsApp.Security;
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("ContentManagement", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireRole(AppRoles.Admin, AppRoles.Editor);
});
options.AddPolicy("ContentPublishing", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireRole(AppRoles.Admin);
policy.RequireClaim("permission", "content.publish");
});
});The ContentManagement policy requires either the Admin or Editor role. The ContentPublishing policy additionally requires the permission=content.publish claim. Therefore, not every Editor must automatically have publishing permission.
Apply a policy to a Controller or action as follows:
[Area("Admin")]
[Authorize(Policy = "ContentManagement")]
public class PostsController : Controller
{
public IActionResult Index()
{
return View();
}
[Authorize(Policy = "ContentPublishing")]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Publish(int id)
{
// Verify that the post exists and can be published.
// Then update its publication state.
await Task.CompletedTask;
return RedirectToAction(nameof(Index));
}
}All requirements in a policy must succeed. This makes named policies preferable to scattering long, repeated conditional expressions throughout Controllers.
Unauthorized requests and status codes
An unauthenticated user who requests a protected endpoint is usually redirected to the login page. An authenticated user who lacks the required role should receive 403 Forbidden. Configure status-code handling to provide a useful response.
app.UseStatusCodePagesWithReExecute("/Error/{0}");Your error Controller can then return a dedicated view for forbidden requests:
public IActionResult Error(int statusCode)
{
return statusCode switch
{
403 => View("Forbidden"),
404 => View("NotFound"),
_ => View("Error")
};
}Middleware order matters. UseAuthentication must run before UseAuthorization. Routing must also be configured correctly so that endpoint metadata can be evaluated.
Role-aware navigation in Razor
Showing an administration link to a user who cannot use it creates a poor experience. You can conditionally render navigation links in a Razor view using User.IsInRole.
@using CmsApp.Security
@if (User.Identity?.IsAuthenticated == true && User.IsInRole(AppRoles.Admin))
{
<a asp-area="Admin" asp-controller="Users" asp-action="Index">
User Management
</a>
}
@if (User.IsInRole(AppRoles.Admin) || User.IsInRole(AppRoles.Editor))
{
<a asp-area="Admin" asp-controller="Posts" asp-action="Index">
Content
</a>
}This conditional user interface improves usability, but it is not the actual security boundary. The real protection remains the [Authorize] or [Authorize(Policy = ...)] metadata on the Controller and action.
Protecting write operations
POST, PUT, and DELETE operations in the administration panel require special attention. Protecting only the GET action while leaving the POST action open can create a serious vulnerability.
[Authorize(Policy = "ContentManagement")]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(EditPostViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Load the real entity from the database.
// Check the current user's role and business permissions as needed.
await Task.CompletedTask;
return RedirectToAction(nameof(Index));
}The fact that a record appears in an administration list does not automatically secure every operation on that record. When an action receives an id, verify that the record exists, that the current user has the required role, and, when applicable, that the user is allowed to modify that particular resource.
Common mistakes
- Forgetting AddRoles: Role services must be registered before
RoleManagerand role-based authorization can work correctly. - Inconsistent role names: Using
Adminin one location andAdministratorin another can cause authorization checks to fail. Use constants. - Only hiding menu items: A user can call a URL directly, so protect Controllers and actions.
- Leaving POST actions unprotected: A secure GET page does not make its data-changing endpoint secure.
- Confusing authentication with authorization: Signing in does not automatically make a user an administrator.
- Using a seeded password in production: Example passwords are for development only; use proper secret management.
- Confusing 401 and 403: 401 indicates that authentication is required, while 403 means the user is known but lacks sufficient permission.
Practice exercise
- Create the
AppRolesclass withAdminandEditorconstants. - Add
AddRoles<IdentityRole>to the Identity configuration. - Seed both roles when the application starts.
- Assign only the
Editorrole to a test user. - Create a Dashboard Controller in the
AdminArea and allow both roles. - Restrict the user-management Controller to the Admin role.
- Create a
ContentPublishingpolicy and apply it to the publish action. - Sign in as the Editor and request the user-management and publishing URLs directly. Verify the authorization results and 403 behavior.
Conclusion
In this lesson, we distinguished authentication from authorization. We registered Admin and Editor roles with Identity, assigned roles to users, and protected the administration area at the Controller level. We used [Authorize(Roles = ...)] for straightforward rules and named policies for more detailed requirements.
You can now connect the administration panel's content operations to a clear authorization model. Remember that security must cover every server-side request, not merely the links and buttons visible in the interface.