rustd / AspnetIdentitySample

476 stars 248 forks source link

Logic doesn't transfer to new Mvc5 webapps VS2013 update4 for Individual User Accounts #47

Open 0xMF opened 9 years ago

0xMF commented 9 years ago

When creating a new Mvc5 webapp in VS2013 Update 4 with Individual User Accounts. The wizard generated IdentityConfig, AccountController, and ManageController are very different from this sample. This means the logic for seeding doesn't work.

public class MyDbInitializer : DropCreateDatabaseAlways<ApplicationDbContext>
    {
        protected override void Seed(ApplicationDbContext context)
        {
            InitializeIdentityForEF(context);
            InitializeMyData(context);
        }

private void InitializeIdentityForEF(ApplicationDbContext context)
        {
            var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));

            string name = "Admin";
            string password = "May-27-2015";

            //Create Role Admin if it does not exist
            if (!RoleManager.RoleExists(name))
            {
                var roleresult = RoleManager.Create(new IdentityRole(name));
            }

            //Create admin=Admin with password=123456
            var admin = new ApplicationUser();
            admin.UserName = name;
            admin.Email = "admin@somewhere.ca";
            admin.EmailConfirmed = true;
            admin.PhoneNumber = "5551234567";
            admin.PhoneNumberConfirmed= true;
            var adminresult = UserManager.Create(admin, password);

            //Add admin Admin to Role Admin
            if (adminresult.Succeeded)
            {
                var result = UserManager.AddToRole(admin.Id, name);
            }
        }

private void InitializeMyData(ApplicationDbContext dc)
        {
            // Custom data initizations
        }
}
0xMF commented 9 years ago

I think I solved this issue for the given seeding values. At minimum, you'd need to initialize the database such that UserName have an email-style string that would be used at logon:


          // Username must be an email-style string for Individual Accounts in Identity v2.1+
          // otherwise you cannot login

            var admin = new ApplicationUser();
            admin.UserName = "admin@somewhere.ca";
            admin.Email = "admin@somewhere.ca";
            var adminresult = UserManager.Create(admin, password);

More testing would be needed for other changes but at least logging in via seeded values is possible now.