Authorization ensures that only the right users can access specific parts of your application. ASP.NET Core MVC provides Role-Based Authorization out of the box, allowing you to restrict access based on assigned user roles (e.g., Admin, Manager, User).
In this article, we’ll walk through implementing role-based authorization in ASP.NET Core MVC with practical code examples.
Step 1: Configure Identity in Program.cs
First, configure ASP.NET Core Identity to handle authentication and roles.
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using YourApp.Data;
var builder = WebApplication.CreateBuilder(args);
// Configure EF Core with SQL Server (or any DB)
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// Add Identity with Roles
builder.Services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapDefaultControllerRoute();
app.Run();
Step 2: Add Role Management to the Database
Update your ApplicationDbContext if needed:
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace YourApp.Data
{
public class ApplicationDbContext : IdentityDbContext<IdentityUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options) { }
}
}
Run migrations to add roles and user tables:
dotnet ef migrations add AddIdentityTables
dotnet ef database update
Step 3: Seed Default Roles
You can seed roles (like Admin, Manager, User) at startup:
using Microsoft.AspNetCore.Identity;
public static class RoleSeeder
{
public static async Task SeedRolesAsync(RoleManager<IdentityRole> roleManager)
{
string[] roles = { "Admin", "Manager", "User" };
foreach (var role in roles)
{
if (!await roleManager.RoleExistsAsync(role))
{
await roleManager.CreateAsync(new IdentityRole(role));
}
}
}
}
In Program.cs:

Join the conversation! Your thoughts help the community grow.