因为在Identity数据库中初始化用户数据,需要设计密码的加密转换,所以尽管与其它数据初始化相同都是发生在EF数据迁移配置的Seed() 方法中,但因此稍有不同。
方法1:
protected override void Seed(SimpleOAuthSample.Models.OAuthDbContext context) { context.Clients.AddOrUpdate( client => client.Name, new Client { Id = "42ff5dad3c274c97a3a7c3d44b67bb42", Name = "Demo Resource Owner Password Credentials Grant Client", ClientSecretHash = new PasswordHasher().HashPassword("client123456"), AllowedGrant = OAuthGrant.ResourceOwner, CreatedOn = DateTimeOffset.UtcNow }); context.Users.AddOrUpdate( user => user.UserName, new IdentityUser("Tugberk") { Id = Guid.NewGuid().ToString("N"), PasswordHash = new PasswordHasher().HashPassword("user123456"), SecurityStamp = Guid.NewGuid().ToString(), Email = "tugberk@example.com", EmailConfirmed = true }); }
从中看出,也就是使用了PasswordHasher().HashPassword()方法。
方法2:
UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); RoleManager<Role> roleManager = new RoleManager<Role>(new RoleStore<Role>(context)); var role = new Role() { Name = "Administrator", Description = "超级管理员", CreateTime = DateTime.Now, }; roleManager.Create(role); context.SaveChanges(); var admin = new ApplicationUser() { Name = "Admin", UserName = "Admin", Email = "admin@host.com", Gender = 0, CreateTime = DateTime.Now, }; userManager.Create(admin, "admin666");
此代码未完全通过验证,但应该是可行的。测试中只顺利添加了Role对象,用户数据添加未能成功,错误之处未知。
The ApplicationDbContext Class from Identity 2.0 Example Project:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { } static ApplicationDbContext() { // Set the database intializer which is run once during application start // This seeds the database with admin user credentials and admin role Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer()); } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } }
The code above sets up two static methods, Create()
, and another, ApplicationDbContext(), which sets a database initializer. This latter method is called during startup, and performs whatever database initialization is established in the ApplicationDbInitializer
class.
If we go back to the IdentityConfig.cs file, we find the ApplicationDbInitializer
defined like so:
The ApplicationDbInitializer Class from the IdentityConfig.cs File:
public class ApplicationDbInitializer : DropCreateDatabaseIfModelChanges<ApplicationDbContext> { protected override void Seed(ApplicationDbContext context) { InitializeIdentityForEF(context); base.Seed(context); } public static void InitializeIdentityForEF(ApplicationDbContext db) { var userManager = HttpContext .Current.GetOwinContext() .GetUserManager<ApplicationUserManager>(); var roleManager = HttpContext.Current .GetOwinContext() .Get<ApplicationRoleManager>(); const string name = "admin@admin.com"; const string password = "Admin@123456"; const string roleName = "Admin"; //Create Role Admin if it does not exist var role = roleManager.FindByName(roleName); if (role == null) { role = new IdentityRole(roleName); var roleresult = roleManager.Create(role); } var user = userManager.FindByName(name); if (user == null) { user = new ApplicationUser { UserName = name, Email = name }; var result = userManager.Create(user, password); result = userManager.SetLockoutEnabled(user.Id, false); } // Add user admin to Role Admin if not already added var rolesForUser = userManager.GetRoles(user.Id); if (!rolesForUser.Contains(role.Name)) { var result = userManager.AddToRole(user.Id, role.Name); } } }
阅读全文

公众号近期文章
赞赏支持
0 Responses to “MVC5 Identity DbContext 初始化用户数据”