Introduction
Authorization is a process that determines what a user is able to do. For example, an Admin user is allowed to install/remove software from a computer, and a non-Admin user can use the software from the computer. It is independent and orthogonal from authentication. However, authorization requires an authentication mechanism. For applications, the first step is always authentication and then authorization.
Identity is a membership system that allows us to add login functionality to our application, and identity may belong to one or more roles. For Example, "User1" belongs to the "Admin" role, and "User2" belongs to the "HR" role.
Using AuthorizeFilter, we can control the access in our MVC/Web API application by specifying this attribute in the controller or action method. Role-based authorization checks whether the login user role has access to the page or not. Here, the developer embeds the roles with their code.
To demonstrate with an example, I have created 3 roles and 3 users and mapped users with roles. I have achieved this by using the following code.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
// Other configurations...
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
CreateRoles(serviceProvider).Wait();
}
private async Task CreateRoles(IServiceProvider serviceProvider)
{
// Initializing custom roles
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var UserManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>();
string[] roleNames = { "Admin", "User", "HR" };
IdentityResult roleResult;
foreach (var roleName in roleNames)
{
var roleExist = await RoleManager.RoleExistsAsync(roleName);
if (!roleExist)
{
// Create the roles and seed them to the database
roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
}
}
IdentityUser user = await UserManager.FindByEmailAsync("[email protected]");
if (user == null)
{
user = new IdentityUser()
{
UserName = "[email protected]",
Email = "[email protected]",
};
await UserManager.CreateAsync(user, "Test@123");
}
await UserManager.AddToRoleAsync(user, "Admin");
IdentityUser user1 = await UserManager.FindByEmailAsync("[email protected]");
if (user1 == null)
{
user1 = new IdentityUser()
{
UserName = "[email protected]",
Email = "[email protected]",
};
await UserManager.CreateAsync(user1, "Test@123");
}
await UserManager.AddToRoleAsync(user1, "User");
IdentityUser user2 = await UserManager.FindByEmailAsync("[email protected]");
if (user2 == null)
{
user2 = new IdentityUser()
{
UserName = "[email protected]",
Email = "[email protected]",
};
await UserManager.CreateAsync(user2, "Test@123");
}
await UserManager.AddToRoleAsync(user2, "HR");
}

Obeid SPosted May 26, 2020, 6:07 PM
Good example how manage user by cheakbox add or remove from roles and how join them with contoller action by code after publisher application thanks
S NischalaPosted Jan 23, 2019, 4:37 AM
I am getting an error saying CANNOT OPEN DATABASE. please help
Nguyễn HuyPosted Nov 18, 2018, 9:49 PM
Thanks you very very much!!
Akhilesh MaithaniPosted Oct 16, 2018, 5:23 AM
Hi Jignesh, I've followed your article, it is working fine, but I've one query that is after login I want to access a get user list API only by ADMIN role, but when I pass token in autherization header it is always given 401 unauthorized error although I 've login with admin credentials. Please help me why this is happing.
Bo JiaoPosted Oct 12, 2018, 10:10 PM
Great! Your project works.
ihtesham qaziPosted Aug 18, 2018, 11:10 PM
Hi Jignesh, How can i use this code in my Razor Pages application. I am getting this error, No service for type 'Microsoft.AspNetCore.Identity.RoleManager`1[Microsoft.AspNetCore.Identity.IdentityRole]' has been registered. Please help.