Xander.PasswordValidator – In a Web Application

In the last post I introduced Xander.PasswordValidator and showed the basics of how to configure it. In this post I’m going to show the PasswordValidationAttribute and how you can use it in your ASP.NET MVC application.

PasswordValidation attribute

At its simplest, all you need to do is to decorate a property in your model with the PasswordValidationAttribute, like this:

  public class SomeModel
  {
     [PasswordValidation]
     public string Password { get; set; }






   
    // Other stuff goes here
  }

That will validate the password based on the settings in the config file, which I discussed briefly in my previous post, and I’ll go into more detail later.

Registering the Password Validator

In order for the file paths to custom word lists to be resolved correctly in a web application you need to register the validator in the Application_Start() method in your web application’s HttpApplication derived class. (Or anywhere before first use).

For example, the Application_Start() method may look like this:

protected void Application_Start()
{
   PasswordValidatorRegistration.Register(); // Register password validator
   AreaRegistration.RegisterAllAreas();
   RegisterGlobalFilters(GlobalFilters.Filters);
   RegisterRoutes(RouteTable.Routes); }

Validating settings from code

As the settings can get quite complex they cannot be set directly in the attribute that you use to decorate the model. Instead they can be set elsewhere and referenced in the attribute.

The settings can be configured as normal then added to the PasswordValidationSettingsCache. For example:

var settings = new PasswordValidationSettings();
settings.NeedsNumber = true;
settings.NeedsSymbol = true;
settings.MinimumPasswordLength = 6;
settings.StandardWordLists.Add(StandardWordList.FemaleNames);
settings.StandardWordLists.Add(StandardWordList.MaleNames);
settings.StandardWordLists.Add(StandardWordList.Surnames);
settings.StandardWordLists.Add(StandardWordList.MostCommon500Passwords);
PasswordValidationSettingsCache.Add("StandardRules", settings);

This code would typically be placed in the Application_Start() method, after registering the password validator.

The important line is the last one. It adds the setting tot he cache with the name “StandardRules”. That can then be references in the attribute later. Like this:

public class MyModel
{
  [PasswordValidation("StandardRules")]
  public string Password { get; set; } 
}

The PasswordValidationAttribute references the entry in the cache, which is then retrieved to perform the validation.

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s