0

I am new to asp.net core and want to know how can I add my custom roles in ASP.Net Core. For example seller, buyer, etc. so I can restrict them to some actions.

I am using default ASP.Net Core template with individual user authentication for now.

R. Richards
  • 24,603
  • 10
  • 64
  • 64
  • Possible duplicate of [How to creat roles in asp.net core and assign it to user](http://stackoverflow.com/questions/42471866/how-to-creat-roles-in-asp-net-core-and-assign-it-to-user) – SynerCoder May 16 '17 at 12:32
  • if you are looking for something ready built that provides a ui for managing user roles, take a look at my cloudscribe core project https://github.com/joeaudette/cloudscribe – Joe Audette May 16 '17 at 13:39

1 Answers1

3

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

Temi Lajumoke
  • 2,350
  • 1
  • 14
  • 14
  • Improvements, make the method static and If you dont want the app to start without those Roles in the DB, dont use async. – MarchalPT Apr 22 '21 at 09:53