Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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");
like image 209
legrojan Avatar asked May 10 '16 16:05

legrojan


3 Answers

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;
like image 118
Rion Williams Avatar answered Nov 14 '22 13:11

Rion Williams


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

like image 31
c0deslayer Avatar answered Nov 14 '22 12:11

c0deslayer


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);   
                }
            }
        }
like image 7
djack109 Avatar answered Nov 14 '22 11:11

djack109