How it works...

Django contains a set of default password validators:

  • UserAttributeSimilarityValidator ensures that any password that's chosen is not too similar to certain attributes of the user. By default, the similarity ratio is set to 0.7 and the attributes that are checked are the username, first and last name, and email address. If any of these attributes contains multiple words, each word is checked independently.
  • MinimumLengthValidator checks that the password that's entered is at least the minimum number of characters in length. By default, passwords must be eight or more characters long.
  • CommonPasswordValidator refers to a file containing a list of passwords that are often used, and hence are insecure. The list Django uses by default contains 1,000 such passwords.
  • NumericPasswordValidator verifies that the password that's entered is not made up entirely of numbers.

When you use the startproject management command to create a new project, these are added with their default options as the initial set of validators. In this recipe, we've shown how these options can be adjusted for our project needs, increasing the minimum length of passwords to 12 characters.

For UserAttributeSimilarityValidator, we have also reduced max_similarity to 0.5, which means that passwords must differ more greatly from user attributes than the default.

Looking at password_validation.py, we have defined two new validators:

  • MaximumLengthValidator is very similar to the built-in one for minimum length, ensuring that the password is no longer than the default of 24 characters
  • SpecialCharacterInclusionValidator checks that one or more special characters – defined as the $, %, :, #, and ! symbols by default – are found within the given password

Each validator class has two required methods:

  • The validate() method performs the actual checks against the password argument. Optionally, a second user argument will be passed when a user has been authenticated.
  • We must also provide a get_help_text() method, which returns a string describing the validation requirements for the user.

Finally, we add the new validators to the settings in order to override the defaults to allow up to a 32-character maximum length for the password, and to be able to add the symbols {, }, ^, and & to the default special character list.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset