简体   繁体   中英

ASP.NET Identity 3.0 Entity Framework Database Seeding

I'm playing with ASP.NET 5 RC1 and am using Identity 3.0 to provide authentication using usernames/passwords, using the built in ASPNET schema and EF7.

For testing purposes, I'm trying to seed the database with roles and users, using a static method called from Startup.cs. The following code works for adding roles, but not for users. (I couldn't find any sample code for using the new RoleManager and UserManager classes in Identity 3). Am I using the correct method call to UserManager here?

        if (!context.Roles.Any(r => r.Name == "Admin"))
        {
            var store = new RoleStore<IdentityRole>(context);
            var manager = new RoleManager<IdentityRole>(store, null, null, null, null, null);
            var role = new IdentityRole { Name = "Admin" };
            manager.CreateAsync(role);
        }

        if (!context.Roles.Any(r => r.Name == "User"))
        {
            var store = new RoleStore<IdentityRole>(context);
            var manager = new RoleManager<IdentityRole>(store, null, null, null, null, null);
            var role = new IdentityRole { Name = "User" };
            manager.CreateAsync(role);
        }

        if (!context.Users.Any(u => u.UserName == "darin"))
        {
            var store = new UserStore<ApplicationUser>(context);
            var manager = new UserManager<ApplicationUser>(store, null, null, null, null, null, null, null, null, null);
            var user = new ApplicationUser { UserName = "darin", Email = "dherle@gmail.com" };
            manager.CreateAsync(user, "admin");
            manager.AddToRoleAsync(user, "Admin");
        }

        if (!context.Users.Any(u => u.UserName == "chris"))
        {
            var store = new UserStore<ApplicationUser>(context);
            var manager = new UserManager<ApplicationUser>(store, null, null, null, null, null, null, null, null, null);
            var user = new ApplicationUser { UserName = "chris", Email = "dan@gmail.com" };
            manager.CreateAsync(user, "chris");
            manager.AddToRoleAsync(user, "User");
        }

I am not sure why it is not working for you. It could be from where you are calling the seeding method from? Eg It was duplicating user accounts when I called it from an action in a controller for example.

The database seeding worked for me with RC1 when I followed the instructions on this link .

The problem is the CreateAsync call in the user creation block. When you call manager.CreateAsync(user, "chris"), you are trying to create the user with UserName "chris" with password "chris". It is possible that such password doesn't meet the security restrictions of the Identity Framework.

In any case, the solution is simple:

 var user = new ApplicationUser { UserName = "chris", Email = "chris@chris.com" }; PasswordHasher<ApplicationUser> ph = new PasswordHasher<ApplicationUser>(); user.PasswordHash = ph.HashPassword(user, "admin3##"); //More complex password manager.CreateAsync(user); manager.AddToRoleAsync(user, "admin"); 

I checked the existing boilerplate code in the ManageController. It seems that need to set modifier async for the Seeding method, and use the await where appropriate to get the seeding done.

    public static async void SeedData(this IApplicationBuilder app)
    {
        var db = app.ApplicationServices.GetService<ApplicationDbContext>();

        db.Database.Migrate();
        //If no role found in the Roles table
        //RoleStore needs using Microsoft.AspNet.Identity.EntityFramework;
        var identityRoleStore = new RoleStore<IdentityRole>(db);
        var identityRoleManager = new RoleManager<IdentityRole>(identityRoleStore, null, null, null, null, null);

            var adminRole = new IdentityRole { Name = "ADMIN" };
        await identityRoleManager.CreateAsync(adminRole);



            var officerRole = new IdentityRole { Name = "OFFICER" };
        await identityRoleManager.CreateAsync(officerRole);




        var userStore = new UserStore<ApplicationUser>(db);
        var userManager = new UserManager<ApplicationUser>(userStore, null, null, null, null, null, null, null, null, null);


        var danielUser = new ApplicationUser { UserName = "DANIEL", Email = "DANIEL@EMU.COM" };
        PasswordHasher<ApplicationUser> ph = new PasswordHasher<ApplicationUser>();
         danielUser.PasswordHash = ph.HashPassword(danielUser, "P@ssw0rd!1"); //More complex password
        await userManager.CreateAsync(danielUser);

        await userManager.AddToRoleAsync(danielUser, "ADMIN");



           var susanUser = new ApplicationUser { UserName = "SUSAN", Email = "SUSAN@EMU.COM" };
           susanUser.PasswordHash = ph.HashPassword(susanUser, "P@ssw0rd!2"); //More complex password
        await userManager.CreateAsync(susanUser);

        await userManager.AddToRoleAsync(susanUser, "ADMIN");



            var randyUser = new ApplicationUser { UserName = "RANDY", Email = "RANDY@EMU.COM" };
        randyUser.PasswordHash = ph.HashPassword(randyUser, "P@ssw0rd!3"); //More complex password
        await userManager.CreateAsync(randyUser);

        await userManager.AddToRoleAsync(randyUser, "OFFICER");






        var thomasUser = new ApplicationUser { UserName = "THOMAS", Email = "THOMAS@EMU.COM" };
      thomasUser.PasswordHash = ph.HashPassword(thomasUser, "P@ssw0rd!4"); //More complex password

        await userManager.CreateAsync(thomasUser);
        await userManager.AddToRoleAsync(thomasUser, "OFFICER");

        var benUser = new ApplicationUser { UserName = "BEN", Email = "BEN@EMU.COM" };
        benUser.PasswordHash = ph.HashPassword(benUser, "P@ssw0rd!5"); //More complex password

        await userManager.CreateAsync(benUser);

        await userManager.AddToRoleAsync(benUser, "OFFICER");


          if (db.Courses.FirstOrDefault() == null)
          {
              Course ditCourse = new Course()
              {
                  CourseAbbreviation = "DIT",
                  CourseName = "DIPLOMA IN INFORMATION TECHNOLOGY",
                  CreatedById = randyUser.Id,
                  UpdatedById = thomasUser.Id
              };
              db.Courses.Add(ditCourse);
              Course dbitCourse = new Course()
              {
                  CourseAbbreviation = "DIPLOMA IN BUSINESS INFORMATION TECHNOLOGY",
                  CourseName = "DBIT",
                  CreatedById = thomasUser.Id,
                  UpdatedById = thomasUser.Id
              };
              db.Courses.Add(dbitCourse);
              Course dismCourse = new Course()
              {
                  CourseAbbreviation = "DISM",
                  CourseName = "DIPLOMA IN INFOCOMM SECURITY MANAGEMENT",
                  CreatedById = thomasUser.Id,
                  UpdatedById = benUser.Id
              };
              db.Courses.Add(dismCourse);

          }

        db.SaveChanges();

        // TODO: Add seed logic here


    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM