1

I have managed to seed the admin's details like the username and password, so they appear in the table. However, the issue I am having is the role "admin" is not being saved anywhere in the table. Am I missing something here? I am new to asp.net core so I'm just trying to wrap my head around it.

Below is my seeding class:

public class ApplicationDbInitializer
{
    public static void SeedUsers(UserManager<IdentityUser> userManager)
    {
        if (userManager.FindByEmailAsync("abc@outlook.com").Result == null)
        {
            IdentityUser user = new IdentityUser
            {
                UserName = "abc@outlook.com",
                Email = "abc@outlook.com"
            };

            IdentityResult result = userManager.CreateAsync(user, "Passwordtest123!").Result;

            if (result.Succeeded)
            {
                userManager.AddToRoleAsync(user, "Admin").Wait();
            }
        }
    }
}

Below is my configure method signature:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, UserManager<IdentityUser> userManager)

Below is me invoking my seed method:

ApplicationDbInitializer.SeedUsers(userManager);

Below is my add identity:

    services.AddIdentity<IdentityUser, IdentityRole>()
         .AddEntityFrameworkStores<RestaurantWebContext>();

Is there something in the code that is missing, I can't see admin show up in the role table or the user table.

Tony Ngo
  • 19,166
  • 4
  • 38
  • 60
KB_Shayan
  • 632
  • 8
  • 24

2 Answers2

2

You need to seed the Roles as well, then link the User to the Role you want.

Check this answer for more information of how you can seed the data.

Hameed
  • 1,497
  • 9
  • 12
0

You can view my full code here

Below is an example

var user = new User
{
    Id = new Guid("a1add451-7dd2-46fd-9877-1996e3f1fb4c").ToString(),
    Email = "",
    NormalizedEmail = "".ToUpper(),
    UserName = "",
    NormalizedUserName = "tony5".ToUpper(),
    EmailConfirmed = true,
    PhoneNumberConfirmed = true,
    LockoutEnabled = false,
    SecurityStamp = Guid.NewGuid().ToString()
};

using (var context = new ApplicationDbContext(
    serviceProvider.GetRequiredService<DbContextOptions<ApplicationDbContext>>()))
{
    var roles = new[]
        {"Owner", "Administrator", "Editor", "ContentWriter"};

    var roles1 = new[]
        {"Administrator"};

    var roles2 = new[]
        {"Editor"};

    var roles4 = new[]
        {"Owner", "Administrator"};

    if (!context.Roles.Any())
    {
        foreach (var role in roles)
        {
            var roleStore = new RoleStore<ApplicationRole>(context);

            await roleStore.CreateAsync(new ApplicationRole
            {
                Name = role,
                NormalizedName = role.ToUpper()
            });
        }
    }

    if (!context.Users.Any())
    {
        await SeedUser(user, context, serviceProvider, roles4);
    }
}


private static async Task SeedUser(
    User user, 
    ApplicationDbContext context, 
    IServiceProvider serviceProvider,
    string[] roles)
{
    var password = new PasswordHasher<User>();
    var hashed = password.HashPassword(user, "123456");
    user.PasswordHash = hashed;
    var userStore = new UserStore<User>(context);

    await userStore.CreateAsync(user);
    await EnsureRole(serviceProvider, user.Email, roles);
    await context.SaveChangesAsync();
}
Tony Ngo
  • 19,166
  • 4
  • 38
  • 60