How to seed an Admin user in EF Core 2.1.0?

我怕爱的太早我们不能终老 提交于 2019-12-17 18:27:38

问题


I have an ASP.NET Core 2.1.0 application using EF Core 2.1.0.

How do I go about seeding the database with Admin user and give him/her an Admin role? I cannot find any documentation on this.


回答1:


As user cannot be seeded in a normal way in Identity just like other tables are seeded using .HasData() of .NET Core 2.1.

Seed Roles in .NET Core 2.1 using code given below in ApplicationDbContext Class :

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);

        modelBuilder.Entity<IdentityRole>().HasData(new IdentityRole { Name = "Admin", NormalizedName = "Admin".ToUpper() });
    }

Seed Users With Roles by Following the steps given below.

Step 1: New class creation

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

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

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

Step 2: Now Modify ConfigureServices method in Startup.cs class.

Before Modification:

services.AddDefaultIdentity<IdentityUser>()
            .AddEntityFrameworkStores<ApplicationDbContext>();

After Modification:

services.AddDefaultIdentity<IdentityUser>().AddRoles<IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>();

Step 3: Modify parameters of Configure Method in Startup.cs class.

Before Modification :

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        //..........
    }

After modification :

public void Configure(IApplicationBuilder app, IHostingEnvironment env, UserManager<IdentityUser> userManager)
    {
        //..........
    }

Step 4 : Calling method of our Seed (ApplicationDbInitializer) class:

ApplicationDbInitializer.SeedUsers(userManager);



回答2:


Actually a User Entity can be seeded in OnModelCreating, one thing to consider: the IDs should be predefined. If type string is used for TKey identity entities, then there is no problem at all.

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);
    // any guid
    const string ADMIN_ID = "a18be9c0-aa65-4af8-bd17-00bd9344e575";
    // any guid, but nothing is against to use the same one
    const string ROLE_ID = ADMIN_ID;
    builder.Entity<IdentityRole>().HasData(new IdentityRole
    {
        Id = ROLE_ID,
        Name = "admin",
        NormalizedName = "admin"
    });

    var hasher = new PasswordHasher<UserEntity>();
    builder.Entity<UserEntity>().HasData(new UserEntity
    {
        Id = ADMIN_ID,
        UserName = "admin",
        NormalizedUserName = "admin",
        Email = "some-admin-email@nonce.fake",
        NormalizedEmail = "some-admin-email@nonce.fake",
        EmailConfirmed = true,
        PasswordHash = hasher.HashPassword(null, "SOME_ADMIN_PLAIN_PASSWORD"),
        SecurityStamp = string.Empty
    });

    builder.Entity<IdentityUserRole<string>>().HasData(new IdentityUserRole<string>
    {
        RoleId = ROLE_ID,
        UserId = ADMIN_ID
    });
}



回答3:


Here is how I did it in the end. I created a DbInitializer.cs class to do the seeding of all my data (including the admin user).

Here's the code for the methods relating to the seeding of the user accounts:

private static async Task CreateRole(RoleManager<IdentityRole> roleManager, 
ILogger<DbInitializer> logger, string role)
{
  logger.LogInformation($"Create the role `{role}` for application");
  IdentityResult result = await roleManager.CreateAsync(new IdentityRole(role));
  if (result.Succeeded)
  {
    logger.LogDebug($"Created the role `{role}` successfully");
  }
  else
  {
    ApplicationException exception = new ApplicationException($"Default role `{role}` cannot be created");
    logger.LogError(exception, GetIdentiryErrorsInCommaSeperatedList(result));
    throw exception;
  }
}

private static async Task<ApplicationUser> CreateDefaultUser(UserManager<ApplicationUser> userManager, ILogger<DbInitializer> logger, string displayName, string email)
{
  logger.LogInformation($"Create default user with email `{email}` for application");

  ApplicationUser user = new ApplicationUser
  {
    DisplayUsername = displayName,
    Email = email,
    UserName = email
  };

  IdentityResult identityResult = await userManager.CreateAsync(user);

  if (identityResult.Succeeded)
  {
    logger.LogDebug($"Created default user `{email}` successfully");
  }
  else
  {
    ApplicationException exception = new ApplicationException($"Default user `{email}` cannot be created");
    logger.LogError(exception, GetIdentiryErrorsInCommaSeperatedList(identityResult));
    throw exception;
  }

  ApplicationUser createdUser = await userManager.FindByEmailAsync(email);
  return createdUser;
}

private static async Task SetPasswordForUser(UserManager<ApplicationUser> userManager, ILogger<DbInitializer> logger, string email, ApplicationUser user, string password)
{
  logger.LogInformation($"Set password for default user `{email}`");
  IdentityResult identityResult = await userManager.AddPasswordAsync(user, password);
  if (identityResult.Succeeded)
  {
    logger.LogTrace($"Set password `{password}` for default user `{email}` successfully");
  }
  else
  {
    ApplicationException exception = new ApplicationException($"Password for the user `{email}` cannot be set");
    logger.LogError(exception, GetIdentiryErrorsInCommaSeperatedList(identityResult));
    throw exception;
  }
}

My Program.cs looks like this:

public class Program
{
  public static async Task Main(string[] args)
  {
    var host = BuildWebHost(args);

    using (var scope = host.Services.CreateScope())
    {
      var services = scope.ServiceProvider;
      Console.WriteLine(services.GetService<IConfiguration>().GetConnectionString("DefaultConnection"));
      try
      {
        var context = services.GetRequiredService<PdContext>();
        var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
        var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>();

        var dbInitializerLogger = services.GetRequiredService<ILogger<DbInitializer>>();
        await DbInitializer.Initialize(context, userManager, roleManager, dbInitializerLogger);
      }
      catch (Exception ex)
      {
        var logger = services.GetRequiredService<ILogger<Program>>();
        logger.LogError(ex, "An error occurred while migrating the database.");
      }
    }

    host.Run();
  }

  public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
    .UseStartup<Startup>()
    .Build();
}



回答4:


If you are referring to Identity users, the way we did was to add hardcoded values in DbContext.OnModelCreating:

builder.Entity<Role>().HasData(new Role { Id = 2147483645, Name = UserRole.Admin.ToString(), NormalizedName = UserRole.Admin.ToString().ToUpper(), ConcurrencyStamp = "123c90a4-dfcb-4e77-91e9-d390b5b6e21b" });

And user:

builder.Entity<User>().HasData(new User
        {
            Id = 2147483646,
            AccessFailedCount = 0,
            PasswordHash = "SomePasswordHashKnownToYou",
            LockoutEnabled = true,
            FirstName = "AdminFName",
            LastName = "AdminLName",
            UserName = "admin",
            Email = "admin@gmail.com",
            EmailConfirmed = true,
            InitialPaymentCompleted = true,
            MaxUnbalancedTech = 1,
            UniqueStamp = "2a1a39ef-ccc0-459d-aa9a-eec077bfdd22",
            NormalizedEmail = "ADMIN@GMAIL.COM",
            NormalizedUserName = "ADMIN",
            TermsOfServiceAccepted = true,
            TermsOfServiceAcceptedTimestamp = new DateTime(2018, 3, 24, 7, 42, 35, 10, DateTimeKind.Utc),
            SecurityStamp = "ce907fd5-ccb4-4e96-a7ea-45712a14f5ef",
            ConcurrencyStamp = "32fe9448-0c6c-43b2-b605-802c19c333a6",
            CreatedTime = new DateTime(2018, 3, 24, 7, 42, 35, 10, DateTimeKind.Utc),
            LastModified = new DateTime(2018, 3, 24, 7, 42, 35, 10, DateTimeKind.Utc)
        });

builder.Entity<UserRoles>().HasData(new UserRoles() { RoleId = 2147483645, UserId = 2147483646 });

I wish there was some better/cleaner way to do it.



来源:https://stackoverflow.com/questions/50785009/how-to-seed-an-admin-user-in-ef-core-2-1-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!