ASP.NET Identity passwords requirements configuration
Dec 30, 2018
Using ASP.NET Core Identity is great out of the box to manage users in a web app.
The default configuration give pretty standard requirements for passwords when users are creating accounts.
The most simple way to change the settings can be found in the documentation
This is great and will be enough in many cases.
You could also move the settings in a seperate method to avoid cluttering the ConfigureServices method.
Now if we want to make something a bit more complex, for example making sure that the password doesn’t contain the username, we’ll have to implement the IPasswordValidator interface.
We also need to set it up in the Startup.cs to have it called on password validation.
This works and is easy enough to put together but what if we want to have all of our password validation in one place to make maintenance easier?
For example, let’s add the length validation to our MyPasswordValidator class.
Now if you run this code and send the password pass123, you will get a validation error saying that you must provide a password with at least 8 characters.
This is because the default validator still runs when you use the AddPasswordValidator to set up your custom validator.
Knowing that, it’s easy to skip the default validation. Registering the IPasswordValidatorbefore the AddIdentity method does it will do the trick.
We have basically replaced AddPasswordValidator so we do not need it anymore. We actually could not use it for this purpose since it’s an extension method for the IdentityBuilder type.