如何在EF Core 2.1.0中为Admin用户设定种子?

时间:2018-06-10 15:02:43

标签: asp.net-core asp.net-core-2.1 ef-core-2.1

我有一个使用EF Core 2.1.0的ASP.NET Core 2.1.0应用程序。

如何使用管理员用户为数据库播种并为他/她提供管理员角色?我找不到任何关于此的文件。

5 个答案:

答案 0 :(得分:27)

因为不能像在其他表中使用.NET Core 2.1的.HasData()那样为用户以常规方式在Identity中进行种子。

使用下面ApplicationDbContext类中给出的代码,在.NET Core 2.1中

种子角色

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() });
    }
请按照以下步骤操作

使用角色来种子用户

步骤1:创建新课程

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();
            }
        }       
    }   
}

步骤2:现在修改ConfigureServices类中的Startup.cs方法。

修改前:

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

修改后:

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

步骤3:修改Configure类中的Startup.cs方法的参数。

修改前:

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

修改后:

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

第4步:我们的Seed(ApplicationDbInitializer)类的调用方法:

ApplicationDbInitializer.SeedUsers(userManager);

答案 1 :(得分:17)

实际上,User实体可以植入OnModelCreating中,需要考虑的一件事:ID应该是预定义的。如果类型string用于TKey身份实体,那么就没有问题。

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
    });
}

答案 2 :(得分:16)

ASP.Net Core 3.1

这就是我使用EntityTypeBuilder的方式:

角色配置:

public class RoleConfiguration : IEntityTypeConfiguration<IdentityRole>
{
    private const string adminId = "2301D884-221A-4E7D-B509-0113DCC043E1";
    private const string employeeId = "7D9B7113-A8F8-4035-99A7-A20DD400F6A3";
    private const string sellerId = "78A7570F-3CE5-48BA-9461-80283ED1D94D";
    private const string customerId = "01B168FE-810B-432D-9010-233BA0B380E9";

    public void Configure(EntityTypeBuilder<IdentityRole> builder)
    {

        builder.HasData(
                new IdentityRole
                {
                    Id = adminId,
                    Name = "Administrator",
                    NormalizedName = "ADMINISTRATOR"
                },
                new IdentityRole
                {
                    Id = employeeId,
                    Name = "Employee",
                    NormalizedName = "EMPLOYEE"
                },
                new IdentityRole
                {
                    Id = sellerId,
                    Name = "Seller",
                    NormalizedName = "SELLER"
                },
                new IdentityRole
                {
                    Id = customerId,
                    Name = "Customer",
                    NormalizedName = "CUSTOMER"
                }
            );
    }
}

用户配置:

public class AdminConfiguration : IEntityTypeConfiguration<ApplicationUser>
{
    private const string adminId = "B22698B8-42A2-4115-9631-1C2D1E2AC5F7";

    public void Configure(EntityTypeBuilder<ApplicationUser> builder)
    {
        var admin = new ApplicationUser
        {
            Id = adminId,
            UserName = "masteradmin",
            NormalizedUserName = "MASTERADMIN",
            FirstName = "Master",
            LastName = "Admin",
            Email = "Admin@Admin.com",
            NormalizedEmail = "ADMIN@ADMIN.COM",
            PhoneNumber = "XXXXXXXXXXXXX",
            EmailConfirmed = true,
            PhoneNumberConfirmed = true,
            BirthDate = new DateTime(1980,1,1),
            SecurityStamp = new Guid().ToString("D"),
            UserType = UserType.Administrator                
        };

        admin.PasswordHash = PassGenerate(admin);

        builder.HasData(admin);
    }

    public string PassGenerate(ApplicationUser user)
    {
        var passHash = new PasswordHasher<ApplicationUser>();
        return passHash.HashPassword(user, "password");
    }
}

向用户分配角色:

 public class UsersWithRolesConfig : IEntityTypeConfiguration<IdentityUserRole<string>>
    {
        private const string adminUserId = "B22698B8-42A2-4115-9631-1C2D1E2AC5F7";
        private const string adminRoleId = "2301D884-221A-4E7D-B509-0113DCC043E1";

        public void Configure(EntityTypeBuilder<IdentityUserRole<string>> builder)
        {
            IdentityUserRole<string> iur = new IdentityUserRole<string>
            {
                RoleId = adminRoleId,
                UserId = adminUserId
            };

            builder.HasData(iur);
        }
    }

最后在数据库上下文类中:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    //If you have alot of data configurations you can use this (works from ASP.Net core 2.2):

    //This will pick up all configurations that are defined in the assembly
    modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());

    //Instead of this:
    modelBuilder.ApplyConfiguration(new RoleConfiguration());
    modelBuilder.ApplyConfiguration(new AdminConfiguration());
    modelBuilder.ApplyConfiguration(new UsersWithRolesConfig());
}

答案 3 :(得分:0)

这是我最后的做法。我创建了一个data_pg_df@data[data_pg_df@data$Region == input$regionInput, ] 类来为所有数据(包括管理员用户)做种子。

screenshot

以下是与用户帐户播种有关的方法的代码:

DbInitializer.cs

我的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; } } 如下:

Program.cs

答案 4 :(得分:-2)

如果您是指身份用户,那么我们要做的就是在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" });

和用户:

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 });

我希望有一些更好/更清洁的方法。