Creating users with no password using ASP.NET Identity

Sam Parsons picture Sam Parsons · Nov 19, 2015 · Viewed 13.5k times · Source

I have been given the requirement to provide the ability to create users through the UI with no password. I am trying to accomplish this using ASP.NET Identity.

I am able to successfully create a user without a password using the UserManager's Create method:

if (vm.ShouldHavePassword)
{
    userManager.Create(userToInsert, vm.Password);
}
else
{
    userManager.Create(userToInsert);
}

After the call to the Create method, the test user gets successfully saved into our AspNetUsers table. And when I do not provide a password, the PasswordHash column in our AspNetUsers table is set to NULL.

My issue is, I cannot login as the test user that does not have a password. The following is the method call that we use to validate a user's credentials:

result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false);

I attempted to login as a test user that has a NULL PasswordHash multiple times. To do this, I do not provide a password in our login form. As a result, a NULL password is passed into the PasswordSignInAsync method. The return value of this method call is always SignInStatus.Failure.

Using ASP.NET Identity, how can I configure my code to correctly authenticate user credentials when the credentials contain a NULL password, and the user in the database contains a NULL PasswordHash? Is such a thing even possible?

Answer

Alfredo R picture Alfredo R · Aug 12, 2016

Yes you can. ASP.NET Identity Framework is fully customizable. Just override PasswordValidator.ValidateAsync and PasswordHasher.VerifyHashedPassword methods like this:

internal class CustomPasswordValidator: PasswordValidator
{
    public override async Task<IdentityResult> ValidateAsync(string item)
    {
        if (string.IsNullOrEmpty(item)) return IdentityResult.Success;
        return await base.ValidateAsync(item);
    }
}

internal class CustomPasswordHasher : PasswordHasher
{
    public override PasswordVerificationResult VerifyHashedPassword(string hashedPassword, string providedPassword)
    {
        if (hashedPassword == null && string.IsNullOrEmpty(providedPassword))
            return PasswordVerificationResult.Success;
        return base.VerifyHashedPassword(hashedPassword, providedPassword);
    }
}

And set them like this:

    var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));

    manager.PasswordValidator = new CustomPasswordValidator();
    manager.PasswordHasher = new CustomPasswordHasher();