Creating passwordless users using an ASP.NET identifier

I was given the requirement to provide users with the ability to create users through an interface without a password. I am trying to accomplish this using ASP.NET Identity.

I can successfully create a user without a password using the UserManager Create method:

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

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

My problem: I cannot log in as a test user who does not have a password. The following is a call to the method that we use to verify user credentials:

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

, NULL PasswordHash . . NULL PasswordSignInAsync. SignInStatus.Failure.

ASP.NET, , NULL, NULL PasswordHash? ?

+4
3

, . Asp.Net Identity Framework . PasswordValidator.ValidateAsync PasswordHasher.VerifyHashedPassword :

    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);
        }
    }

:

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

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

, ( AspNetUsers), db. , , , PasswordHash. , SignInManager.SignIn , SignInManager.PasswordSignIn

..

var user = db.AspNetUsers.FirstOrDefault(p=>p.UserName); //alternatively, you can find the user using Email, Id or some other unique field
if(user.PasswordHash == null)
     await SignInManager.SignInAsync(user, true, true);
else
     await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false);

, .

+2

, . : Dummy/Common #, ,

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

result = await SignInManager.PasswordSignInAsync(model.UserName, "someDummy123$", model.RememberMe, shouldLockout: false);
0
source

Source: https://habr.com/ru/post/1663490/


All Articles