Asp.net-mvc – Cannot login on ASP.NET Identity 2 site after programmatic user creation

asp.net-identity-2asp.net-mvcasp.net-mvc-5

I have a new MVC 5 razor, EF 6 web application using ASP.NET Identity 2 for the membership system. When I create the users manually using the Register link on the web page, it goes fine. I can create the user, I can then login with the given password and then logout.

I don't know how to use the database initializer with migration for Identity 2, there are countless examples with Identity 1 and other alpha and beta versions which only serve to confuse people. Since I don't know that yet, I use a temporary MVC view to install the membership.

I see the the view executes properly, I see the users and roles as well as the associations of users with roles in the database. I also see that the users have a hashed password in the record.

However, after doing that I cannot login to the identity system (local) with the plain text passwords I used in the Create method, why? BTW I have omitted the try/catch and checks for user and role creations (they execute without error).

DbContext ctx = ApplicationDbContext.Create();
transaction = ctx.Database.BeginTransaction();
RoleManager<IdentityRole> roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(ctx));
var roleAdmin = roleManager.Create(new IdentityRole("Admin"));

var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ctx));
ApplicationUser userAdmin = new ApplicationUser { Id = "admin", Email = "me@there.com", UserName = "admin" };
            userManager.Create(userAdmin, "Test_2013");
userManager.AddToRole(userAdmin.Id, "Admin");
userManager.Update(userAdmin);

transaction.Commit(); 

So after that if I attempt to login to the account with the email address and the Test_2013 password I get an error indicating the username/password is incorrect.

Best Answer

After much investigations on the actual database (Identity 2) and the web I came to the conclusion nobody knew :) In fact of the millions of sites that have outdated information about Identity and even place Identity 2.0 code that is already outdated I had to dig into it further with the SQL Profiler and the SQL Management Studio.

In Identity 2.0 there is an Id property that is an nvarchar() but actually contains a Guid. I wonder why Microsoft didn't just made it a uniqueidentifier type?! I was setting this property when I should have left it alone (let it autogenerate it).

Likewise in Identity 2.0 there is an UserName field which I was populating with the username. It seems UserName should be the same as Email, otherwise attempts to login will simply fail.

Related Topic