Check if a password is valid using ASP.NET Identity 2
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);
}
}
}
Related videos on Youtube
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, 2022Comments
-
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 about 6 yearsIn .NET Core, you have
userManager.PasswordValidators
, just loop through them and do the same as above, or don.t do.Succeed
to get theIdentityResult
to get the errors. -
djack109 over 4 yearsThe 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 modifiedIdentityUser