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

1

5

I am using asp.net core 2.2 default web site template and authentication selected as individual user account. How can i create an "Admin" role and assign it to a user so that i can use role in controller to filter the access and let them see different pages. Here is what i found on the internet until now, but it doesn't work, because it says : ApplicationUser could not be found

private void CreateRoles(IServiceProvider serviceProvider)
        {

            var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
            var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
            Task<IdentityResult> roleResult;
            string email = "[email protected]";

            //Check that there is an Administrator role and create if not
            Task<bool> hasAdminRole = roleManager.RoleExistsAsync("Administrator");
            hasAdminRole.Wait();

            if (!hasAdminRole.Result)
            {
                roleResult = roleManager.CreateAsync(new IdentityRole("Administrator"));
                roleResult.Wait();
            }

            //Check if the admin user exists and create it if not
            //Add to the Administrator role

            Task<ApplicationUser> testUser = userManager.FindByEmailAsync(email);
            testUser.Wait();

            if (testUser.Result == null)
            {
                ApplicationUser administrator = new ApplicationUser();
                administrator.Email = email;
                administrator.UserName = email;

                Task<IdentityResult> newUser = userManager.CreateAsync(administrator, "_AStrongP@ssword!");
                newUser.Wait();

                if (newUser.Result.Succeeded)
                {
                    Task<IdentityResult> newUserRole = userManager.AddToRoleAsync(administrator, "Administrator");
                    newUserRole.Wait();
                }
            }

        }

Any help in having an Admin for my app will be greatly appreciated.

Disruptive answered 5/5, 2019 at 16:29 Comment(4)
Take a look here: learn.microsoft.com/en-us/aspnet/core/security/authorization/…Shashaban
@Shashaban and how can i assign a role to an user..?Disruptive
ApplicationUser could not be found; When are you getting this error? before compile or during runtime?Erosion
@Erosion before i even build the appDisruptive
C
7

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("[email protected]");
    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();
}
Crab answered 6/5, 2019 at 2:34 Comment(6)
It does get the job almost done. It creates the role "Admin" and assign it to the user i gave, but i receive an error when pressing the login button in the nav-bar. InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.SignInManager1[Microsoft.AspNetCore.Identity.IdentityUser]' while attempting to activate 'WebApplication1.Areas.Identity.Pages.Account.LoginModel'.Disruptive
Do you modify the _LoginPartial.cshtml to use new ApplicationUser ?Crab
search your application to find any IdentityUser exists ? try replace with ApplicationUserCrab
it looks like that was the problem, but after doing this modifications, the new role is not saved in the database.Disruptive
debug in CreateUserRoles , step by step to confirm where cause the problemCrab
Found the problem, i was not waiting for the role to be created. Thanks a lot, you really helped me.Disruptive

© 2022 - 2024 — McMap. All rights reserved.