Skip to content

How To: Set up simple password complexity requirements

Clément Prod'homme edited this page Mar 9, 2021 · 13 revisions

Recommendation

Best solution would be so use a 3rd party library like strong_password that tries to comply with NIST requirements:

https://github.com/bdmac/strong_password

Manual solution

Here is a simple method of adding a password strength / complexity requirement to devise without using devise security extension (using extension is recommended.)

Example: add the following line to app/models/user.rb. Edit Regex to your liking

  validate :password_complexity
  
  def password_complexity
    # Regexp extracted from https://stackoverflow.com/questions/19605150/regex-for-password-must-contain-at-least-eight-characters-at-least-one-number-a
    return if password.blank? || password =~ /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,70}$/

    errors.add :password, 'Complexity requirement not met. Length should be 8-70 characters and include: 1 uppercase, 1 lowercase, 1 digit and 1 special character'
  end

Afterwards, password created by the user (or admin) must meet the regex requirements.

If the password length is checked by another method (such as config.password_length), this suits better:

  def password_complexity
    # Regexp extracted from https://stackoverflow.com/questions/19605150/regex-for-password-must-contain-at-least-eight-characters-at-least-one-number-a
    return if password.blank? || password =~ /(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-])/

    errors.add :password, 'Complexity requirement not met. Please use: 1 uppercase, 1 lowercase, 1 digit and 1 special character'
  end
Clone this wiki locally