如何在asp core2中正确播种用户身份?

时间:2017-12-28 02:04:58

标签: c# asp.net-identity asp.net-core-2.0 seeding

我有这个种子类,它无法在users表中插入记录,

我认为使用CreateAsync是不正确的,因为该方法不是异步的,用户管理器不会为记录播种。所以我尝试使用哈希密码手动播种,但我无法登录。我发布了两种方法

为什么没有在数据库初始化中插入用户信息? 的 1。使用UserManager CreateAsync

       public void SeedData()
        {
            using (var serviceScope = scopeFactory.CreateScope())
            {
                using (var context = serviceScope.ServiceProvider.GetService<ArtCoreDbContext>())
                {
         if (!context.ApplicationUser.Any())
                  {
               var user = new ApplicationUser
                        {
                            CityId = context.Cities.Where(g => g.Name == "Abu Nusair").SingleOrDefault().Id,
                            CountryId = context.Countries.Where(g => g.Name == "Jordan").SingleOrDefault().Id,
                             Email = "maizer85@hotmail.com",
                            FirstName = "Zaid",
                            GenderId = context.Genders.Where(g => g.Name == "Female").SingleOrDefault().Id,
                            IsActive = true,
                            LastName = "Abu Maizar",
                            MaritalStatusId = context.MaritalStatus.Where(g => g.Name == "Single").SingleOrDefault().Id,
                            NationalityId = context.Nationalities.Where(g => g.Name == "Jordanian").SingleOrDefault().Id,
                            OccupationId = context.Occupations.Where(g => g.Name == "MD").SingleOrDefault().Id,
                             PersonalPhotoUrl = null,
                             PhoneNumber = "4243244990",
                             PhoneNumberConfirmed = false,
                             PostalCode = 91335,
                             SocialSecurityNo = "AABBCC",
                            StateId = context.States.Where(g => g.Name == "Amman").SingleOrDefault().Id,
                            StatusId = context.Statuses.Where(g => g.Name == "Active").SingleOrDefault().Id,
                             UserName = "Zaid",

                        };
                         userManager.CreateAsync(user, "String@string85");
                         context.SaveChanges();
                    }

                }
            }
        }

2。手动种子,

         public void SeedData()
            {
                using (var serviceScope = scopeFactory.CreateScope())
                {
                    using (var context = serviceScope.ServiceProvider.GetService<ArtCoreDbContext>())
                    {
                        if (!context.ApplicationUser.Any())
                        {

                            context.ApplicationUser.AddRange(
                             new ApplicationUser
                             {
                                 Id = Guid.NewGuid().ToString("N"),
                                 AccessFailedCount = 0,
                                 AdminLevel = "LA",
                                 ApartmentNo = 0,
                                 CityId = context.Cities.Where(g => g.Name == "Abu Nusair").SingleOrDefault().Id,
                                 ConcurrencyStamp = Guid.NewGuid().ToString("N"),
                                 ContactAddress = "USA",
                                 ContactCountry = "USA",
                                 CountryId = context.Countries.Where(g => g.Name == "Jordan").SingleOrDefault().Id,
                                 DateCreated = DateTime.UtcNow,
                                 Email = "maizer85@hotmail.com",
                                 EmailConfirmed = false,
                                 FirstName = "Zaid",
                                 GenderId = context.Genders.Where(g => g.Name == "Female").SingleOrDefault().Id,
                                 IsActive = true,
                                 LastLoggedIn = DateTime.UtcNow,
                                 LastName = "Abu Maizar",
                                 Locality = "LA",
                                 LockoutEnabled = true,
                                 LockoutEnd = null,
                                 MaritalStatusId = context.MaritalStatus.Where(g => g.Name == "Single").SingleOrDefault().Id,
                                 NationalityId = context.Nationalities.Where(g => g.Name == "Jordanian").SingleOrDefault().Id,
                                 NormalizedEmail = "MAIZER85@HOTMAIL.COM",
                                 NormalizedUserName = "ZAID",
                                 OccupationId = context.Occupations.Where(g => g.Name == "MD").SingleOrDefault().Id,
                                 PasswordHash = HashPassword("Zaid@core85"),
                                 PersonalPhotoUrl = null,
                                 PhoneNumber = "4243244990",
                                 PhoneNumberConfirmed = false,
                                 PostalCode = 91335,
                                 SecurityStamp = Guid.NewGuid().ToString("N"),
                                 SocialSecurityNo = "AABBCC",
                                 StateId = context.States.Where(g => g.Name == "Amman").SingleOrDefault().Id,
                                  StatusId = context.Statuses.Where(g => g.Name == "Active").SingleOrDefault().Id,
                                 StreetDirection = "LA",
                                 StreetNo = "123231",
                                 TwoFactorEnabled = false,
                                 UserName = "Zaid",
                                 VerificationPhotoUrl = null

                             }
                        );
                            context.SaveChanges();
                        }
                    }
                }
            }

密码哈希方法,

public static string HashPassword(string password)
        {
            byte[] salt;
            byte[] buffer2;
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }
            using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, 0x10, 0x3e8))
            {
                salt = bytes.Salt;
                buffer2 = bytes.GetBytes(0x20);
            }
            byte[] dst = new byte[0x31];
            Buffer.BlockCopy(salt, 0, dst, 1, 0x10);
            Buffer.BlockCopy(buffer2, 0, dst, 0x11, 0x20);
            return Convert.ToBase64String(dst);
        }

2 个答案:

答案 0 :(得分:1)

这里有一个类似的主题:Creating Asp.net Identity user in Seed method of Db Initializer

因此您需要使用非异步扩展方法。添加Microsoft.AspNet.Identity程序集和using Microsoft.AspNet.Identity

有一个例子:https://stackoverflow.com/a/27499759/3710672

关于手动播种。我认为您无法登录导致您使用的HashPassword功能与UserManager在检查密码时使用的算法不同。

要使其正常工作,请尝试使用userManager.PasswordHasher.HashPassword(..)方法而不是您的功能。

在您的ApplicationUser中:

...
PasswordHash = userManager.PasswordHasher.HashPassword("Zaid@core85"),
...

答案 1 :(得分:0)

这个实现对我有用

public void SeedData()
        {
            using (var serviceScope = scopeFactory.CreateScope())
            {
                using (var context = serviceScope.ServiceProvider.GetService<ArtCoreDbContext>())
                {
         if (!context.ApplicationUser.Any())
                  {
               var user = new ApplicationUser
                        {
                            CityId = context.Cities.Where(g => g.Name == "Abu Nusair").SingleOrDefault().Id,
                            CountryId = context.Countries.Where(g => g.Name == "Jordan").SingleOrDefault().Id,
                             Email = "maizer85@hotmail.com",
                            FirstName = "Zaid",
                            GenderId = context.Genders.Where(g => g.Name == "Female").SingleOrDefault().Id,
                            IsActive = true,
                            LastName = "Abu Maizar",
                            MaritalStatusId = context.MaritalStatus.Where(g => g.Name == "Single").SingleOrDefault().Id,
                            NationalityId = context.Nationalities.Where(g => g.Name == "Jordanian").SingleOrDefault().Id,
                            OccupationId = context.Occupations.Where(g => g.Name == "MD").SingleOrDefault().Id,
                             PersonalPhotoUrl = null,
                             PhoneNumber = "4243244990",
                             PhoneNumberConfirmed = false,
                             PostalCode = 91335,
                             SocialSecurityNo = "AABBCC",
                            StateId = context.States.Where(g => g.Name == "Amman").SingleOrDefault().Id,
                            StatusId = context.Statuses.Where(g => g.Name == "Active").SingleOrDefault().Id,
                             UserName = "Zaid",

                        };
                    Task<IdentityResult> createTask = userManager.CreateAsync(user, "Temp_123");
                    createTask.Wait();

                    }

                }
            }
        }