This article explains ASP.NET Roles and a step-by-step guide on how to add role-based authentication to your ASP.NET Core application.
ASP.NET Identity is a membership system that provides an easy way to manage user authentication and authorization, including support for OAuth 2.0 and OpenID Connect. In this article, we will explore the mechanics of how ASP.NET Identity works and provide real-world code examples for adding role-based authentication to your ASP.NET application.
Prerequisites
Setting up the identity system. You can follow the steps in this guide to set it up on your app.
Step 1: Adding Roles to the Identity System
The first step is to add roles to the Identity system. Open the Program.cs
file and add the following code:
builder.Services.AddIdentity<IdentityUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders() .AddDefaultUI();
The code AddIdentity<IdentityUser, IdentityRole>()
is used in ASP.NET Core applications to configure the Identity system.
- The
AddIdentity
method registers the Identity system services in the dependency injection container of the application. It also configures the default settings for Identity, including password requirements, user lockout settings, and token lifespan. - The
IdentityUser
andIdentityRole
classes are the default user and role models provided by Identity. These classes define the properties and methods required to manage users and roles in an application. By passingIdentityUser
andIdentityRole
as generic parameters to theAddIdentity
method, the application is configured to use these classes as the default user and role models. This configuration allows the application to use the built-in functionality of Identity, such as user registration, password management, and role-based authorization, without the need for additional configuration or customization. AddEntityFrameworkStores<ApplicationDbContext>()
is a method that is used to configure the Identity system in an ASP.NET Core application to use Entity Framework as the storage provider for user and role data.AddDefaultTokenProviders()
is a method used to configure default token providers for the Identity system. Token providers are used for generating and validating tokens in the Identity system, such as password reset and email confirmation tokens. By default, ASP.NET Core Identity provides several built-in token providers for these scenarios.- `AddDefaultUI()` also method registers the default views and UI elements for the Identity system, including login, registration, and password reset pages.
By the way, did you know that we offer a unique online course that boosts your C# career? Check it out here!
Step 2: Seeding Roles to the Database
The next step is to seed roles to the database. In the Program.cs
file add the following code:
using (var scope = app.Services.CreateScope()) { var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>(); var roles = new[] { "Admin", "Manager", "Member" }; foreach (var role in roles) { if (!await roleManager.RoleExistsAsync(role)) { await roleManager.CreateAsync(new IdentityRole(role)); } } }
This code creates three roles in the database: Admin
, Manager
, and Member
.
The ASP.NET Identity system is built on top of the Dependency Injection (DI) system in ASP.NET. When you add the Identity system to your application, several services are registered with the DI system. Some of the important services are:
UserManager<TUser>
: Provides the APIs for managing users, such as creating, updating, and deleting users.SignInManager<TUser>
: Provides the APIs for signing in and out users, and managing user sessions.RoleManager<TRole>
: Provides the APIs for managing roles, such as creating, updating, and deleting roles.IUserStore<TUser>
: Provides the APIs for storing and retrieving user data.IRoleStore<TRole>
: Provides the APIs for storing and retrieving role data.
We used `RoleManager<IdentityRole>` to create some roles and use them in our application.
Step 3: Adding Authorization Policies
The next step is to add authorization policies to control access to different parts of the application based on roles. In the Program.cs
file add the following code:
builder.Services.AddAuthorization(options => { options.AddPolicy("Admin", policy => policy.RequireRole("Admin")); options.AddPolicy("Manager", policy => policy.RequireRole("Manager")); options.AddPolicy("Member", policy => policy.RequireRole("Member")); });
The code configures the Authorization middleware. The Authorization middleware examines incoming requests and checks whether the user making the request has the necessary permissions to access the requested resource.
We added three “policies” to the Authorization system: Admin
, Manager
, and Member
. Each policy requires the corresponding role. As an example, `options.AddPolicy(“Admin”, policy => policy.RequireRole(“Admin”))` is a method that is used to define an authorization policy that requires a user to have the role of Admin
to be able to access a particular resource.
Step 4: Restricting Users’ Access to Controllers and Actions
The final step is to add the [Authorize]
attribute to controllers and actions to require authentication and authorization. Open the controller or action that you want to secure and add the [Authorize]
attribute:
[Authorize(Policy = "Admin")] public IActionResult AdminOnly() { // Controller action code here }
The Roles
parameter specifies the roles that are allowed to access the action. This code secures the AdminOnly
action and only allows users with the Admin
role to access it. If you want to skyrocket your C# career, check out our powerful ASP.NET full-stack web development course that also covers test-driven development.
Step 5: Restricting Users’ Access to Views
You can restrict users’ access to certain elements of views based on the users’ roles. Look at this example:
@using Microsoft.AspNetCore.Identity @inject SignInManager<IdentityUser> SignInManager @inject UserManager<IdentityUser> UserManager @if (User.IsInRole("Administrator")) { <!-- Display the blog post creation and editing UI --> } @if (User.IsInRole("User") || User.IsInRole("Administrator")) { <!-- Display the blog post viewing UI --> }
In this code, the SignInManager and UserManager services are injected into the view using the @inject directive. The User.IsInRole method is used to check if the current user has a specific role, and display the appropriate UI based on the user’s role.
ASP.NET Roles Summary
In this article, we have covered the steps required to add role-based authentication to your ASP.NET Core application. By following these steps, you should now have a working authorization system that controls access to different parts of the application based on roles.