Saturday, July 21, 2007

Validating a Strong Password in Login Controls

When using both the Create User Wizard and the Change Password controls, users are allowed to enter any password they want. This opens new security holes because too many users enter passwords that are common words. These passwords are easy for the user to remember, but they are also easy for a hacker to figure out. Because the Login controls don't check for weak password vulnerabilities, your site is at risk.
The hack in this section adds validation capabilities to passwords. We're simply going to add a RegularExpressionValidator control. To get started, perform the following actions:
Add a Create User Wizard to a Web form.
Drag a Regular Expression Validator to the right side of the same table cell as the Password TextBox.
Change the RegularExpressionValidator ErrorMessage property to "Must have at least 1 number, 1 special character, and more than 6 characters."
Change the RegularExpressionValidator Text property to *.
Change the RegularExpressionValidator ControlToValidate property to Password.
Change the RegularExpressionValidator ValidationExpression property to "(?=∘.{6,}$)(?=.*\d)(?=.*\W+)(?![.\n]).*$".
Important
As its name suggests, a RegularExpressionValidator control uses what is called a regular expression to perform its validation. Regular expressions are a pattern matching language, which at first glance look cryptic and terse. However, once you know how to use them, you are very likely to find them fast and powerful. A good regular expressions site on the Web is http://regexlib.com.
The HTML for the cell where the Password is located should now look like this:

TextMode="Password">
ControlToValidate="Password"
ErrorMessage="Password is required."
ToolTip="Password is required."
ValidationGroup="CreateUserWizard1">*

ControlToValidate="Password"
ErrorMessage="Must have at least 1 number, 1 special character, and more
than 6 characters."
ValidationExpression=
"(?=^.{6,}$)(?=.*\d)(?=.*\W+)(?![.\n]).*$">*


You can cut and paste the highlighted RegularExpressionValidator element from the preceding HTML into the Password cell of your own templated Create User Wizard. While you're at it, you can add a RegularExpressionValidator control to the Create User Wizard e-mail address, too. The RegularExpressionValidator ValidationExpression property already has a pop-up dialog in which a regular expression for e-mail is available for selection from a list of other regular expressions.
The same technique works for the Change Password control. After adding the Change Password control to your page, select Create Template, and use the same RegularExpressionValidator described above. The only difference will be that you should set the ControlToValidate property to NewPassword

No comments: