Building the Logon Page


Open the NorthwindWeb project that you created at the beginning of the chapter to create the Web pages. Now you need to create the logon page. When you are done, the page will look similar to that in Figure 12-6. Add the controls and set the properties of the controls as indicated in Table 12-1 to the Logon.aspx page.

Table 12-1: The Logon Page Controls and Properties

Control

Property

Value

Label

Text

Logon Form

Font

Large

Label

Text

User Name

Textbox

ID

txtUserName

Label

Text

Password

Textbox

ID

txtPassword

TextMode

Password

Label

ID

lblMessage

Button

Name

btnLogon

Text

Logon

Button

Name

btnNewUser

Text

New User

click to expand
Figure 12-6: The NorthwindWeb logon page

Because you just created this little application, there are no users in the system. You will code the New User functionality first.

Note

As you go through these exercises, you will probably think of many more things that you can do. This is not intended to be a complete text on the subject of Web security; it is intended as an overview to give you some experience with creating a secure Web site structure using .NET.

Before you start coding, you need to add a reference to your Web service so that you can call the validate and add routines. To do this, right-click the References node in the Solution Explorer and select Add Web Reference. Enter the Uniform Resource Locator (URL) for the Web service you created (http://localhost/Northwind/service1.asmx) or select the link for Web Services on the Local Machine. Select localhost/Northwind/Service1 and click Add Reference.

Return to your Logon.aspx form and double-click the btnNewUser button to go to its code page and create the click event for this method. Add the following lines to the top of the code module (above the class):

 Option Explicit On Option Strict On Imports System.Web Imports System.Web.Security Imports System.Security.Cryptography Imports NorthwindWeb.Localhost Imports System.Configuration 

Implementing the Add New User Functionality

Next, add the code from Listing 12-7 to the btnNewUser_Click method.

Listing 12-7: The Add New User Functionality

start example
 Dim objSecurity As Service1 Dim blnValid As Boolean Dim bytPassword(), bytEncrypted() As Byte Dim strEncryptedPassword As String Dim i As Integer Dim sec As New SHA1Managed Dim ue As New System.Text.UnicodeEncoding Try      bytPassword = ue.GetBytes(txtPassword.Text)      bytEncrypted = sec.ComputeHash(bytPassword)      For i = 0 To bytEncrypted.Length - 1      strEncryptedPassword += bytEncrypted(i).ToString      Next      objSecurity = New Service1      blnValid = objSecurity.AddUser(txtUserName.Text, strEncryptedPassword)      If blnValid = False Then           Throw New Exception("Failed to add user.")      End If      FormsAuthentication.SetAuthCookie(txtUserName.Text, False)      Response.Redirect("secure/Employees.aspx") Catch exc As Exception      lblMessage.Text = "An error occurred while adding user " & txtUserName.Text End Try 
end example

The first line converts the password string into a series of bytes for use in the creation of the hash:

 bytPassword = ue.GetBytes(txtPassword.Text) 

The next line actually creates the hash and returns the result as a byte array:

 bytEncrypted = sec.ComputeHash(bytPassword) 

This loop extracts all of the values from the hashed array and stores them in one string variable so that you can easily store the value in the database:

 For i = 0 To bytEncrypted.Length - 1      strEncryptedPassword += bytEncrypted(i).ToString Next 

Next you call the Web service to add the values to the UserList table. After that, you set the authentication cookie using this line:

 FormsAuthentication.SetAuthCookie(txtUserName.Text, False) 

The False argument just states that you do not want to persist this cookie after the session ends. And finally, once you have indicated that the user has been authenticated, you direct them to the secure section of the application using the following line:

 Response.Redirect("secure/Employees.aspx") 

If you tried to redirect the user without setting the authentication cookie first, you would be returned to this logon page because ASP.NET would not recognize that the user had been authenticated.

Tip

Another method you can use to redirect users is the FormsAuthentication.RedirectFromLoginPage method. Say, for example, that a user has bookmarked a secured page in your application and they use this link to go directly to the page. If the user has not been authenticated, they will be redirected to the login page. After they have successfully logged on, then the application will automatically redirect them to the page they were trying to reach originally. You will not be using this method on this small application because you are not creating a "default" page that the user would go to first.

Lastly, note that when an error occurs you only tell the user of the application that an error occurred while adding the user—you do not tell them what the error was.

Note

Way too many Web sites fail to authenticate a user and then give a hacker a helpful message along the lines of "Login for user X failed because the password was invalid." Well, now the hacker knows that they have a valid username, so it will not be long before they get the password right.

You should now be able to run the Web application, supply a username and password, click the New User button, and be redirected to your empty employee.aspx page.

Implementing the Validate User Functionality

Now you will implement the logon (Validate User) functionality that is almost identical to the previous method. Enter the code in Listing 12-8 to validate the user.

Listing 12-8: Validating the User

start example
 Private Sub btnLogon_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnLogon.Click      Dim objSecurity As Service1      Dim blnValid As Boolean      Dim bytPassword(), bytEncrypted() As Byte      Dim strEncryptedPassword As String      Dim i As Integer      Dim sec As New SHA1Managed      Dim ue As New System.Text.UnicodeEncoding      bytPassword = ue.GetBytes(txtPassword.Text)      bytEncrypted = sec.ComputeHash(bytPassword)      For i = 0 To bytEncrypted.Length - 1           strEncryptedPassword += bytEncrypted(i).ToString      Next      objSecurity = New Service1      blnValid = objSecurity.ValidateUser(txtUserName.Text, _      strEncryptedPassword)      If blnValid = False Then          Response.Redirect("AccessDenied.aspx")      Else          FormsAuthentication.SetAuthCookie(txtUserName.Text, False)          Response.Redirect("secure/Employees.aspx")      End If End Sub 
end example

This method creates a hash out of the password and sends the username and hashed password to the database for verification. If there is an entry with that username/password combination, then the user is authenticated; otherwise they are redirected to your access denied page (which you have not coded).

Caution

I had to code this form in this manner because otherwise an error was thrown during the Response.Redirect to the Employees.aspx page. The exception received was a "Thread was being aborted" error. This is possibly because I was working with two betas at the same time (.NET 1.1 beta and Release Candidate 2 of .NET Web Server 2003).




Building Client/Server Applications with VB. NET(c) An Example-Driven Approach
Building Client/Server Applications Under VB .NET: An Example-Driven Approach
ISBN: 1590590708
EAN: 2147483647
Year: 2005
Pages: 148
Authors: Jeff Levinson

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