Wednesday, December 17, 2025

thumbnail

Role-Based Access Control (RBAC) in .NET Core Applications

 Role-Based Access Control (RBAC) in .NET Core Applications


Role-Based Access Control (RBAC) is a security paradigm used to restrict system access to authorized users based on their roles. It's commonly used in applications to enforce policies on who can access what resources or perform what actions within the system.


In .NET Core, RBAC can be implemented easily with the ASP.NET Core Identity system, which provides built-in support for authentication and authorization. You can assign users to roles and define what each role is allowed to access in the application.


This guide will walk you through setting up RBAC in an ASP.NET Core application, including configuring roles, assigning them to users, and applying authorization policies to restrict access to resources.


1. Set Up ASP.NET Core Identity


ASP.NET Core Identity is the built-in system for managing users, roles, and permissions. It includes default implementations for user management, authentication, and authorization.


1.1. Add Required Packages


First, make sure your project includes the necessary packages. If you're starting from a blank ASP.NET Core project, add the following NuGet packages:


dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

dotnet add package Microsoft.EntityFrameworkCore.Tools



If you're using EF Core with SQL Server as the database, these packages will enable you to store user data and roles in a SQL Server database.


1.2. Configure Identity in Startup.cs or Program.cs


In ASP.NET Core 5+, configuration is typically done in the Program.cs file. In earlier versions, it would be in Startup.cs.


public class Program

{

    public static void Main(string[] args)

    {

        CreateHostBuilder(args).Build().Run();

    }


    public static IHostBuilder CreateHostBuilder(string[] args) =>

        Host.CreateDefaultBuilder(args)

            .ConfigureWebHostDefaults(webBuilder =>

            {

                webBuilder.ConfigureServices((context, services) =>

                {

                    // Add DB context and Identity services

                    services.AddDbContext<ApplicationDbContext>(options =>

                        options.UseSqlServer(context.Configuration.GetConnectionString("DefaultConnection")));

                    services.AddDefaultIdentity<ApplicationUser>()

                        .AddRoles<IdentityRole>()

                        .AddEntityFrameworkStores<ApplicationDbContext>();


                    // Add authorization

                    services.AddAuthorization();

                    services.AddRazorPages();

                });

                webBuilder.Configure(app =>

                {

                    var env = app.Environment;

                    if (env.IsDevelopment())

                    {

                        app.UseDeveloperExceptionPage();

                    }

                    else

                    {

                        app.UseExceptionHandler("/Home/Error");

                        app.UseHsts();

                    }


                    app.UseHttpsRedirection();

                    app.UseStaticFiles();


                    app.UseRouting();


                    app.UseAuthentication();

                    app.UseAuthorization();


                    app.MapRazorPages();

                });

            });

}



Here:


ApplicationDbContext is the class representing your EF Core database context, which includes the IdentityDbContext.


ApplicationUser is a custom class that inherits from IdentityUser (optional, you can customize this for extra user fields).


2. Creating Roles


Roles in ASP.NET Core Identity are used to grant specific permissions to groups of users. Common roles might include Admin, User, Manager, etc.


2.1. Add Roles to the Database


To add roles, you need to ensure roles are created in your application’s database. This can be done in SeedData during application startup.


Create a new class like SeedData to initialize roles.


public class SeedData

{

    public static async Task Initialize(IServiceProvider serviceProvider, UserManager<ApplicationUser> userManager)

    {

        var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();

        var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();


        string[] roleNames = { "Admin", "Manager", "User" };

        foreach (var roleName in roleNames)

        {

            var roleExist = await roleManager.RoleExistsAsync(roleName);

            if (!roleExist)

            {

                await roleManager.CreateAsync(new IdentityRole(roleName));

            }

        }


        var adminUser = await userManager.FindByEmailAsync("admin@admin.com");

        if (adminUser == null)

        {

            adminUser = new ApplicationUser

            {

                UserName = "admin@admin.com",

                Email = "admin@admin.com"

            };

            await userManager.CreateAsync(adminUser, "Admin@123");


            await userManager.AddToRoleAsync(adminUser, "Admin");

        }

    }

}



In this code:


We check if roles like Admin, Manager, and User exist; if they don’t, they are created.


We also check if an Admin user exists. If not, one is created and added to the Admin role.


Call the SeedData.Initialize() method during application startup.


2.2. Call SeedData.Initialize() in Program.cs

public class Program

{

    public static void Main(string[] args)

    {

        var host = CreateHostBuilder(args).Build();


        using (var scope = host.Services.CreateScope())

        {

            var services = scope.ServiceProvider;

            var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();

            SeedData.Initialize(services, userManager).Wait();

        }


        host.Run();

    }

}



This ensures that the roles are seeded into the database when the application starts.


3. Assign Roles to Users


Once the roles are set up, you can assign roles to users either manually or programmatically.


3.1. Assign Roles Manually


You can assign roles through ASP.NET Core Identity UI (if you're using the Identity scaffolding) or via UserManager and RoleManager in your application code.


Here’s an example of assigning roles programmatically:


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

if (user != null)

{

    await userManager.AddToRoleAsync(user, "Manager");

}


3.2. Assign Roles During User Registration


You can assign roles to users directly in the registration process:


public class RegisterModel : PageModel

{

    private readonly UserManager<ApplicationUser> _userManager;


    public RegisterModel(UserManager<ApplicationUser> userManager)

    {

        _userManager = userManager;

    }


    public async Task<IActionResult> OnPostAsync(string email, string password, string role)

    {

        var user = new ApplicationUser { UserName = email, Email = email };

        var result = await _userManager.CreateAsync(user, password);


        if (result.Succeeded)

        {

            await _userManager.AddToRoleAsync(user, role);

            return RedirectToPage("Index");

        }


        return Page();

    }

}


4. Role-Based Authorization


Once users are assigned to roles, you can use role-based authorization to restrict access to different parts of your application.


4.1. Applying Role-Based Authorization


In your Razor Pages, Controllers, or Views, you can apply role-based authorization using the [Authorize] attribute.


For Controllers:


[Authorize(Roles = "Admin")]

public class AdminController : Controller

{

    public IActionResult Index()

    {

        return View();

    }

}



For Razor Pages:


@page

@attribute [Authorize(Roles = "Admin")]

<h2>Admin Page</h2>



For Views:


You can check roles in the view by using User.IsInRole:


@if (User.IsInRole("Admin"))

{

    <p>Welcome, Admin!</p>

}


4.2. Custom Policies (Optional)


In addition to roles, you can define custom authorization policies for more granular control.


For example, if you want to allow only users who are in both the Admin role and have been a member for at least one year, you can define a custom policy.


Define the Policy in Program.cs:


services.AddAuthorization(options =>

{

    options.AddPolicy("AdminOnly", policy =>

        policy.RequireRole("Admin"));

    options.AddPolicy("AdminAndLongTimeUser", policy =>

        policy.RequireRole("Admin").RequireClaim("JoinedDate", "1/1/2020"));

});



Apply the Policy in your Controller or Page:


[Authorize(Policy = "AdminAndLongTimeUser")]

public IActionResult LongTimeAdminPage()

{

    return View();

}


5. Testing RBAC


After setting up roles and policies, you should test your RBAC implementation by:


Registering users with different roles.


Verifying that users are only able to access the pages or actions associated with their role.


Trying unauthorized access to ensure the application correctly prevents it.


Conclusion


RBAC in .NET Core is a powerful way to control access to different parts of your application based on user roles. By using ASP.NET Core Identity, you can easily manage users, assign roles, and define role-based authorization policies. This helps in building secure applications where different users have access to different resources depending on their roles.

Learn Dot Net Course in Hyderabad

Read More

Preventing SQL Injection Attacks in Full Stack .NET Development

How to Protect Against Cross-Site Scripting (XSS) in ASP.NET Core

Implementing SSL/TLS in Full Stack .NET Applications

Protecting Your API with Rate Limiting and IP Whitelisting in .NET

Visit Our Quality Thought Institute in Hyderabad

Get Directions 

Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments

About

Search This Blog

Powered by Blogger.

Blog Archive