How to Create Roles in ASP.NET Core and Assign Them to Users

How to create roles in ASP.NET Core and assign them to users?

I have created an action in the Accounts controller that calls a function to create the roles and assign the Admin role to the default user. (You should probably remove the default user in production):

    private async Task CreateRolesandUsers()
{
bool x = await _roleManager.RoleExistsAsync("Admin");
if (!x)
{
// first we create Admin rool
var role = new IdentityRole();
role.Name = "Admin";
await _roleManager.CreateAsync(role);

//Here we create a Admin super user who will maintain the website

var user = new ApplicationUser();
user.UserName = "default";
user.Email = "default@default.com";

string userPWD = "somepassword";

IdentityResult chkUser = await _userManager.CreateAsync(user, userPWD);

//Add default User to Role Admin
if (chkUser.Succeeded)
{
var result1 = await _userManager.AddToRoleAsync(user, "Admin");
}
}

// creating Creating Manager role
x = await _roleManager.RoleExistsAsync("Manager");
if (!x)
{
var role = new IdentityRole();
role.Name = "Manager";
await _roleManager.CreateAsync(role);
}

// creating Creating Employee role
x = await _roleManager.RoleExistsAsync("Employee");
if (!x)
{
var role = new IdentityRole();
role.Name = "Employee";
await _roleManager.CreateAsync(role);
}
}

After you could create a controller to manage roles for the users.

How to create roles in ASP.NET Core 2.2 and assign them to users

The first step is to create the ApplicationUser class which could be used to extend claims :

public class ApplicationUser : IdentityUser
{

}

Modify the _LoginPartial.cshtml to use that class :

@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

Modify the ApplicationDbContext.cs in Data folder to assign ApplicationUser and IdentityRole :

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole, string>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
}

Modify the Startup.cs to enable using the new ApplicationUser and role management :

services.AddDefaultIdentity<ApplicationUser>()
.AddRoles<IdentityRole>()
.AddDefaultUI(UIFramework.Bootstrap4)
.AddEntityFrameworkStores<ApplicationDbContext>();

After that , you could seed to crate role and assign to user like :

private async Task CreateUserRoles(IServiceProvider serviceProvider)
{
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();

IdentityResult roleResult;
//Adding Admin Role
var roleCheck = await RoleManager.RoleExistsAsync("Admin");
if (!roleCheck)
{
//create the roles and seed them to the database
roleResult = await RoleManager.CreateAsync(new IdentityRole("Admin"));
}
//Assign Admin role to the main User here we have given our newly registered
//login id for Admin management
ApplicationUser user = await UserManager.FindByEmailAsync("v-nany@hotmail.com");
await UserManager.AddToRoleAsync(user, "Admin");
}

To use :

public void Configure(IApplicationBuilder app, IHostingEnvironment env,IServiceProvider serviceProvider)
{
.......

app.UseAuthentication();

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});

CreateUserRoles(serviceProvider).Wait();
}

How to assign roles to users using the website interface in ASP.NET Core 2.1

If you want to assign a role to a user in MVC (tested in asp.net core 2.1), you can do the following. I have also created a user here, just to show the injection of the UserManager.

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace MyApp.Controllers
{

public class RolesController : Controller
{
private readonly RoleManager<IdentityRole> _roleManager;
private readonly UserManager<IdentityUser> _userManager;

public RolesController(RoleManager<IdentityRole> roleManager, UserManager<IdentityUser> userManager)
{
_roleManager = roleManager;
_userManager = userManager;
}

[HttpPost]
public async Task<IActionResult> AssignRoleToUser(string _roleName, string _userName)
{
//Created a user
var user = new IdentityUser { UserName = _userName, Email = "xyz@somedomain.tld" };
var result = await _userManager.CreateAsync(user, "[SomePassword]");
if (result.Succeeded)
{
// assign an existing role to the newly created user
await _userManager.AddToRoleAsync(user, "Admin");
}
return View();
}

}
}

How can I add new roles in ASP.Net Core?

I've answered this question multiple times here, and because of the occurrence, I decided to write an article about it here. However, I'll answer it once again.

Here's how you go about it Wajahat

You could do this easily by creating a CreateRoles method in your startup class. This helps check if the roles are created, and creates the roles if they aren't; on application startup. Like so.

private async Task CreateRoles(IServiceProvider serviceProvider)
{
//initializing custom roles
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
string[] roleNames = { "Admin", "Store-Manager", "Member" };
IdentityResult roleResult;

foreach (var roleName in roleNames)
{
var roleExist = await RoleManager.RoleExistsAsync(roleName);
// ensure that the role does not exist
if (!roleExist)
{
//create the roles and seed them to the database:
roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
}
}

// find the user with the admin email
var _user = await UserManager.FindByEmailAsync("admin@email.com");

// check if the user exists
if(_user == null)
{
//Here you could create the super admin who will maintain the web app
var poweruser = new ApplicationUser
{
UserName = "Admin",
Email = "admin@email.com",
};
string adminPassword = "p@$$w0rd";

var createPowerUser = await UserManager.CreateAsync(poweruser, adminPassword);
if (createPowerUser.Succeeded)
{
//here we tie the new user to the role
await UserManager.AddToRoleAsync(poweruser, "Admin");

}
}
}

and then you could call the await CreateRoles(serviceProvider); method from the Configure method in the Startup class.
ensure you have IServiceProvider as a parameter in the Configure class.

To restrict them to some actions. You can easily define what roles have access to certain controllers or controller actions, like so.

[Authorize(Roles="Admin")]
public class ManageController : Controller
{
//....
}

You can also use role-based authorization in the action method like so. Assign multiple roles, if you will

[Authorize(Roles="Admin")]
public IActionResult Index()
{
/*
.....
*/
}

While this works fine, for a much better practice, you might want to read about using policy-based authorization or role checks. You can find it on the ASP.NET core documentation here, or this article I wrote about it here



Related Topics



Leave a reply



Submit