Recipe 16.4. Prompting for a Username and Password


Problem

You need to add a password dialog to an application to prevent unauthorized access to the rest of the program.

Solution

Sample code folder: Chapter 16\LoginTest

Use the standard LoginForm dialog provided by Visual Basic 2005.

Discussion

In Visual Studio 2005, you can add new items to your project, selecting from a variety of predefined forms and other objects. If you select the Project Add Windows Form menu command, one of the form choices you can add is a LoginForm. This form is all set up with User Name and Password text boxes, along with two buttons and a nice graphic. You can modify this dialog to suit your own requirements, perhaps replacing the graphic image with something more appropriate for your business.

The Password text box displays only asterisks as the user enters his password. All TextBox controls have a PasswordChar property, which is normally left blank. Enter an asterisk (or any other character) in this property, and the TextBox displays only the given character. The TextBox.Text property still returns whatever text the user has entered; it's just displayed as all asterisks to mask it from prying eyes.

The following code block shows how hashed values of the User Name and Password text entries can be compared against known hashed values. This code requires the GetHash() function defined in Recipe 16.1:

 Dim result As String ' ----- Store only the hashed values, not the plain text. Dim hashUserName As String = GetHash("AlbertE") Dim hashPassword As String = GetHash("E=MC2") LoginForm1.ShowDialog( ) ' ----- Hash the input values. Dim hashUserInput As String = _    GetHash(LoginForm1.UsernameTextBox.Text) Dim hashPassInput As String = _    GetHash(LoginForm1.PasswordTextBox.Text) ' ----- Test the inputs. If (hashUserName = hashUserInput) AndAlso _       (hashPassword = hashPassInput) Then    result = "Yes, you passed the password test!" Else    result = "I'm sorry, please try again." End If MsgBox(result) 

Normally, it's best not to put the user's name and password directly in the code, as shown here, but for demonstration purposes, it works well. In the next recipe we'll store the hashed password in the registry, where the actual password can't be discovered.

Figure 16-4 shows the LoginForm in action, after the user has entered a username and password, but just before the OK button is clicked or the Enter key pressed.

Figure 16-4. Visual Basic 2005's customizable standard LoginForm





Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net