Search code examples
c#asp.net-mvcazureasp.net-identitystartup

Startup.cs Add and Configure User method password issue


I have created a method in my Startup.cs file that has the following method in it:

`

private void createRolesandUsers()
        {
            ApplicationDbContext context = new ApplicationDbContext();

            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
            var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));


            // creating first Boss Role and creating a default Boss User    
            if (!roleManager.RoleExists("Boss"))
            {

                // first we create Admin rool   
                var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
                role.Name = "Boss";
                roleManager.Create(role);

                //add a note to get this to rerun?

                //Here we create a Admin super user who will maintain the website                  

                var user = new ApplicationUser();
                user.UserName = "Boss";
                user.Email = "admin@adminaccount.com";

                string userPWD = "Pa$$w0rd";

                var chkUser = UserManager.Create(user, userPWD);

                //Add default User to Role Admin   
                if (chkUser.Succeeded)
                {
                    var result1 = UserManager.AddToRole(user.Id, "Boss");

                }
            }

`

I then call this method from Configuration. It works great to create the user and the role of Boss. I can confirm the user has been created and also the role when I remotely log into my Azure app's SQL database. Unfortunately, I am unable to log into the account, I have double checked the user name and password and copied and pasted both into the email input and password input. Does any one know what could be wrong with my code to cause this and any suggestions to fix it?

Thank you for your help with this in advance!


Solution

  • Default MVC template creates login page which requires Email and password BUT login controller uses SignInManager.PasswordSignInAsync which requires UserName (not Email which comes to the method).

    Quick fix:

    update dbo.AspNetUsers set UserName=Email where UserName='Boss'
    

    (and login using email == username).

    Longer fix: rewrite login.cshtml, LoginViewModel, and [HtmlPost]Login accordingly.