Check if a password is valid using ASP.NET Identity 2

18,793

Solution 1

You may be able to use the PasswordValidator.ValidateAsync() method to determine if a password meets the criteria defined in your UserManager :

var valid = (await UserManager.PasswordValidator.ValidateAsync("pass")).Succeeded;

Solution 2

You can simply use PasswordValidator to check for password validity and errors as shown below:

var passwordValidator = new PasswordValidator<IdentityUser>();
var result = await passwordValidator.ValidateAsync(_userManager, null, "your password here");

if (result.Succeeded)
{
    // Valid Password
}
else
{
    // Check the error messages in result.Errors
}

Above solution works for Asp.Net Core 2.2

Solution 3

In Net.Core 2.2, I did this. I collect the errors into a string list as I send them back via JSON using a mechanism that standard throughout my application. Thanks to cularbytes

        List<string> passwordErrors = new List<string>();

        var validators = _userManager.PasswordValidators;

        foreach(var validator in validators)
        {
            var result = await validator.ValidateAsync(_userManager, null, newPassword);

            if (!result.Succeeded)
            {
                foreach (var error in result.Errors)
                {
                    passwordErrors.Add(error.Description);   
                }
            }
        }
Share:
18,793

Related videos on Youtube

legrojan
Author by

legrojan

I identify as a Knight and should be address as "Ni!". Not ni or Ni, but Ni!, Ni!s, Ni!self: "Ni! is so handsome!" "Ni!s face is angelical!" "I have been touched by The Knight Ni!self!"

Updated on September 16, 2022

Comments

  • legrojan
    legrojan over 1 year

    On my website, I give the administrators the possibility to change someone's password without entering the old one. I do the following:

    userManager.RemovePassword(oldUser.Id);
    userManager.AddPassword(oldUser.Id, newPassword);
             
    

    However, this changes the password only if the newPassword string complies with the password policy set in the configuration files. AddPassword seems to fail silently when the new password does not fulfil the requirements.

    Is there some simple way to check if a password is valid according to the current policy, apart from the obvious "manual procedure" (check how many upper/lowercase chars there are, how many digits, etc.). I'm looking for something like

    bool valid = IsPasswordValid("pass");
    
  • CularBytes
    CularBytes about 6 years
    In .NET Core, you have userManager.PasswordValidators, just loop through them and do the same as above, or don.t do .Succeed to get the IdentityResult to get the errors.
  • djack109
    djack109 over 4 years
    The solution does indeed work in Core 2.2. However, it doesn't work if like I have, modified the IdentityUser class. The userManager.PasswordValidators version does work tho with modified IdentityUser