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");
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;
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
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With