Chapter 16. Securing Your Application

Most Web applications include password-protected areas. For example, if you are building an online store, you’ll need to force users to register before they buy a product. Or, if you are creating an employee directory, you might want to password protect the page for adding new employees so that only administrators of the application can access the page.

In this chapter, you will learn how to password protect pages in your Web application by taking advantage of Forms Authentication. In particular, you will learn

  • How to configure authentication and authorization for Forms Authentication

  • How to create a simple login page that enables registered users to log in to your Web application

  • How to authenticate users against a data store

  • How to implement a role-based security system that enables you to group users into different roles

Overview of Forms Authentication

The .NET Framework includes three built-in methods of authenticating users—Windows Authentication, Forms Authentication, and .NET Passport Authentication. All three authentication methods follow a similar model. In other words, if you understand how to configure one, you can configure the other two.

Windows Authentication uses Windows accounts and groups. Microsoft .NET Passport Authentication uses Microsoft Passport user accounts (the same user accounts that are used by such Microsoft services as HotMail and MSN).

In this chapter, we’ll concentrate on Forms Authentication because this is the type of authentication that you are most likely to set up for a Web application. Forms Authentication, unlike the other two authentication models, enables you to store usernames and passwords in a custom data store, such as a database table or XML file.

Authentication and Authorization

Before diving into the topic of Forms Authentication, you need to understand how Microsoft distinguishes between the following two terms:

  • Authentication—The process of identifying a user

  • Authorization—The process of determining the resources a user is allowed to access

Forms Authentication handles authentication by creating a browser cookie that identifies a user. It handles authorization by enabling you to create a configuration file that lists the resources a user is allowed to access.

When you configure Forms Authentication, you need to create two Web.Config files (or a single Web.Config file with two sections). You need to create a Web.Config file that indicates the type of authentication you want to perform, and a Web.Config file that authorizes access to different users or roles.

A minimal authentication Web.Config file looks as follows:

<configuration>
<system.web>
  <authentication mode="Forms" />
</system.web>
</configuration>

This file simply enables Forms Authentication for an application as opposed to Windows or Passport Authentication. The default authentication method, as specified in the Machine.Config file, is Windows Authentication. This configuration file overrides the default setting.

The <authentication> section must be placed in the root Web.Config file for an application. You can enable only one method of authentication for an application. For example, one application cannot use both Forms Authentication and Passport Authentication.

An authentication Web.Config file doesn’t do anything interesting by itself. To password protect pages, you need to add another Web.Config file that contains an <authorization> section. A minimal authorization Web.Config file looks like the following:

<configuration>
<system.web>
  <authorization>
    <deny users="?" />
  </authorization>
  </system.web>
</configuration>

This Web.Config file prevents anonymous (unauthenticated) users from accessing any pages in the current directory or any subdirectory. If an anonymous user attempts to access a page, the user is automatically redirected to a page named Login.aspx.

Tip

By default, unauthorized users are redirected to the application root Login.aspx page. You can supply an alternative path for the Login page by modifying the loginUrl attribute in the authentication Web.Config file as follows:

<configuration>
<system.web>
  <authentication mode="Forms">
    <forms loginUrl="mylogin.aspx" />
  </authentication>
</system.web>
</configuration>

Warning

Forms Authentication only applies to resources mapped into the .NET Framework. By default, it does not apply to HTML, classic ASP, or image files. To apply Forms Authentication to these files, you need to map the proper file extensions to the ASP.NET Framework in the Internet Services Manager.

For example, to protect GIF files, you need to map the .gif file extension to the aspnet_isapi.dll extension under the App Mappings tab. Be aware that mapping new extensions into the ASP.NET Framework has performance implications.

The <authentication> section accepts two different elements: <deny> and <allow>. The <deny> element can be used to deny access to a list of users or roles. The <allow> element enables access.

You can specify users or roles by name. You can also use two special symbols: ? and *. The question mark (?) represents all anonymous users. The asterisk (*) represents all users, regardless of whether they are authenticated.

Consider, for example, the following Web.Config file:

<configuration>
<system.web>
  <authorization>
    <allow users="Jane" />
    <deny users="*" />
  </authorization>
  </system.web>
</configuration>

This authorization Web.Config file denies access to all the pages in a directory to all users except Jane. The <authorization> section uses a first match algorithm. The order of the <allow> and <deny> elements here is important. If you reversed the order, all users, including Jane, would be denied access.

You can add multiple authorization Web.Config files to a single application. For example, you can prevent anonymous users from accessing pages in certain folders and not others. You can also password protect an entire application by adding an <authorization> section to the root Web.Config file.

You should keep in mind that the Web.Config file works by inheritance. Unless you override an authentication section in a lower-level Web.Config file, authentication settings will apply to all the files in a folder and all of its subfolders.

Enabling Forms Authentication

In this section, we’ll walk through each of the steps required to enable Forms Authentication. We’ll password-protect all the pages in a directory named SecretFiles so that only users who log in can view the pages.

The first step is to enable Forms Authentication by modifying the Web.Config file located in the root directory of your application.

  1. Double-click the root Web.Config file in the Solution Explorer window.

  2. Delete all the contents of the Web.Config file (don’t let this make you nervous!).

  3. Enter the following configuration settings:

    <configuration>
    <system.web>
      <authentication mode="Forms" />
    </system.web>
    </configuration>
    
  4. Click the Save button to save the modified Web.Config file.

This Web.Config file enables Forms Authentication for your entire application. Making these modifications does not password protect any pages. However, it is a necessary step before you can password protect a page.

Next, we need to create the Web Form Page that we want to password protect.

  1. Add a new folder to your application named SecretFiles by right-clicking your application name in the Solution Explorer Window and selecting Add, New Folder.

  2. Add a new Web Form Page to the SecretFiles folder by right-clicking SecretFiles in the Solution Explorer window and selecting Add, Add Web Form. Provide the name Secret.aspx for the new Web Form Page and click Open.

  3. Drag a Flow Layout Panel control from under the HTML tab in the Toolbox onto the Secret.aspx page.

  4. Enter the text This Content is Secret! in the Flow Layout Panel.

Finally, to password protect the files in the SecretFiles folder, we must add a second Web.Config file to the SecretFiles folder. This second Web.Config file contains an <authentication> section that prevents anonymous users from accessing the folder.

  1. Right-click the SecretFiles folder in the Solution Explorer window and select Add, Add New Item. When the Add New Item dialog box appears, select Web Configuration File in the Templates panel and click Open.

  2. Delete all the contents of the new Web.Config file.

  3. Enter the following configuration settings into the Web.Config file:

    <configuration>
    <system.web>
      <authorization>
        <deny users="?" />
      </authorization>
      </system.web>
    </configuration>
    
  4. Click Save.

After you complete this last set of steps, all of the files in the SecretFiles folder are password protected. If you right-click the Secret.aspx page in the Solution Explorer window and select Build and Browse, you’ll receive a “404 File Not Found Error” (see Figure 16.1). You have been automatically redirected to a page named Login.aspx that doesn’t exist. We’ll create the Login.aspx page in the next section.

Accessing a password-protected page.

Figure 16.1. Accessing a password-protected page.

Creating a Simple Login Page

If a user attempts to access a password protected page, he or she is automatically redirected to a page named Login.aspx. In this section, you’ll learn how to create a simple forms authentication Login.aspx page (see Figure 16.2).

A simple login page.

Figure 16.2. A simple login page.

Our login page will allow a user to log in only when the user enters the username Administrator and the password Secret. Perform the following steps to add the necessary controls to the Login.aspx page:

  1. Add a new Web Form Page to the root folder of your project named Login.aspx.

  2. Drag a Label control from the Web Forms tab in the Toolbox onto the Designer surface. Clear the Text property of the Label control.

  3. Drag a TextBox control from the Web Forms tab onto the Designer surface and assign the following values to its properties:

    Property

    Value

    ID

    txtUsername

  4. Drag a second TextBox control from the Web Forms tab in the Toolbox onto the Designer surface and assign the following values to its properties:

    Property

    Value

    ID

    txtPassword

    TextMode

    Password

  5. Drag two HTML labels from the HTML tab onto the Designer surface. Enter the text Username for the first label and the text Password for the second label. Position the labels next to the TextBox controls.

  6. Drag a Button control from the Web Forms tab onto the Designer surface.

Next, we need to add the application logic to the page that authenticates the username and password that the user enters into the form.

  1. Double-click the Button control. This will switch you to the Code Editor and create a Button1_Click handler.

  2. Enter the following code for the Button1_Click handler:

    C#

    private void Button1_Click(object sender, System.EventArgs e)
    {
      if (txtUsername.Text == "Administrator" && txtPassword.Text == "Secret")
        System.Web.Security.FormsAuthentication.RedirectFromLoginPage( txtUsername.Text, false );
      else
        Label1.Text = "Invalid Username/Password";
    }
    

    VB.NET

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    VB.NET Handles Button1.Click
      If txtUsername.Text = "Administrator" And txtPassword.Text = "Secret" Then
        System.Web.Security.FormsAuthentication.RedirectFromLoginPage( txtUsername.Text, False)
      Else
        Label1.Text = "Invalid Username/Password"
      End If
    End Sub
    
  3. Right-click the Secret.aspx page (not the Login.aspx page) in the Solution Explorer window and select Build and Browse.

When you complete the last step, the Secret.aspx page will not appear. Instead, you’ll be automatically redirected to the Login.aspx page. If you enter Administrator and Secret, you will be automatically redirected back to the Secret.aspx page (the username and password are case sensitive).

The Button1_Click handler first checks whether the txtUsername and txtPassword TextBox controls contain the values Administrator and Secret. If the values match, the RedirectFromLoginPage() method is called.

The RedirectFromLoginPage() method does two things. First, it issues an Authentication Ticket to the user’s browser. The Authentication Ticket is an encrypted cookie that identifies the user. It also automatically redirects the user back to the original page that the user requested by secretly calling the Response.Redirect() method.

The RedirectFromLoginPage() method accepts two parameters. The first parameter represents a username. The username can be any string, including an email address. The second parameter indicates whether a persistent cookie should be created. When the second parameter has the value true, the user does not have to log in the next time the user visits the Web site. The Authentication cookie is saved persistently on the user’s browser.

Note

The RedirectFromLoginPage() method redirects the user to the original page the user requested. There is a special situation, however, when the user requests the Login.aspx page directly. In that situation, there is no page to which the user can be redirected, so the user is redirected to the Default.aspx page.

Retrieving the Username

After a user has logged in, you can retrieve the user’s username by using the User.Identity.Name property (a property of the Page class). This is useful when you want to customize pages for particular users.

For example, you can display the username on the Secret.aspx page by doing the following:

  1. Double-click the Secret.aspx page in the Solution Explorer window.

  2. Drag a Label control from under the Web Forms tab onto the Designer surface.

  3. Double-click the Designer surface to switch to the Code Editor.

  4. Enter the following code for the Page_Load handler:

    C#

    private void Page_Load(object sender, System.EventArgs e)
    {
      Label1.Text = User.Identity.Name;
    }
    

    VB.NET

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
    VB.NET MyBase.Load
      Label1.Text = User.Identity.Name
    End Sub
    
  5. Right-click the Secret.aspx in the Solution Explorer window and select Build and Browse.

When the Secret.aspx page opens, the username of the current user is displayed in the Label control.

Creating a Sign Out Link

You can add a Sign Out link to the pages in your application by taking advantage of the FormsAuthentication.SignOut() method. This method removes the Authentication Ticket cookie from the user’s browser.

Perform the following steps to create add a Sign Out link to the Secret.aspx page:

  1. Double-click the Secret.aspx page in the Solution Explorer window.

  2. Drag a LinkButton control from under the Web Forms tab on the Toolbox onto the Designer surface.

  3. In the Properties window, assign the value Sign Out to the LinkButton control’s Text property.

  4. Double-click the LinkButton control on the Designer surface. This will switch you to the Code Editor and add a LinkButton1_Click handler.

  5. Enter the following code for the LinkButton1_Click handler:

    C#

    private void LinkButton1_Click(object sender, System.EventArgs e)
    {
    System.Web.Security.FormsAuthentication.SignOut();
    Response.Redirect( "..Login.aspx?ReturnUrl=" + Server.UrlEncode( Request.Path ) );
    }
    

    VB.NET

    Private Sub LinkButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    VB.NET Handles LinkButton1.Click
      System.Web.Security.FormsAuthentication.SignOut()
      Response.Redirect("../Login.aspx?ReturnUrl=" & Server.UrlEncode(Request.Path))
    End Sub
    
  6. Right-click the Secret.aspx page in the Solution Explorer window and select Build and Browse.

When the Secret.aspx page opens, a Sign Out link appears. If you click the Sign Out link, you are redirected to the Login.aspx page. Furthermore, if you attempt to go directly back to the Secret.aspx page after signing out, you are redirected to the Login.aspx page.

The second line of code in the LinkButton1_Click handler performs the redirection. Notice that a query string parameter named ReturnUrl is passed back to the Login.aspx page. The FormsAuthentication.RedirectFromLoginPage() method uses this query string parameter when redirecting a user who has successfully logged in.

Storing Usernames and Passwords in the Web.Config File

In the Login.aspx page that we built in the previous section, we checked whether the user entered the username Administrator and the password Secret. Our application isn’t particularly useful because only one person can ever log in. In this section, you’ll learn how you can store a list of usernames and passwords in the Web.Config file.

Storing usernames and passwords in the Web.Config file is valuable when you need to maintain a limited number of usernames and passwords. For example, if your Web application contains a private section for administrators of the application, you can password protect the section and store a list of valid administrators in the Web.Config file.

Perform the following steps to modify the pages that we created in the previous section:

  1. Double-click the application root Web.Config file in the Solution Explorer window and enter the following configuration settings:

    <configuration>
    <system.web>
      <authentication mode="Forms">
        <forms>
          <credentials passwordFormat="Clear">
          <user name="Bob" password="Secret" />
          <user name="Jane" password="Secret" />
          <user name="Fred" password="Secret" />
          </credentials>
        </forms>
      </authentication>
    </system.web>
    </configuration>
    
  2. Right-click the Login.aspx page in the Solution Explorer window and select Code from the View menu. Modify the Button1_Click handler as follows:

    C#

    private void Button1_Click(object sender, System.EventArgs e)
    {
    if (System.Web.Security.FormsAuthentication.Authenticate( txtUsername.Text, txtPassword
    C#.Text) )
      System.Web.Security.FormsAuthentication.RedirectFromLoginPage( txtUsername.Text, false );
    else
      Label1.Text = "Invalid Username/Password";
    }
    

    VB.NET

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    VB.NET Handles Button1.Click
      If System.Web.Security.FormsAuthentication.Authenticate( txtUsername.Text, txtPassword
    VB.NET.Text) Then
        System.Web.Security.FormsAuthentication.RedirectFromLoginPage( txtUsername.Text, False)
      Else
        Label1.Text = "Invalid Username/Password"
      End If
    End Sub
    
  3. Right-click the Secret.aspx page in the Solution Explorer window and select Build and Browse.

After you complete these steps, you can view the Secret.aspx page only if you enter one of the username and password combinations contained in the application Web.Config file. We modified the Login.aspx page to use the Authenticate() method to check usernames and passwords. The Authenticate() method simply performs a match against usernames and passwords in the Web.Config file.

Note

Note the attribute named passwordFormat included in the <credentials> tag of the Web.Config file. This attribute enables you to store the hash value of a password instead of the password itself in the Web.Config file. If you have multiple people administering a Web server and you don’t want everyone’s passwords in plain view, it is a good idea to hide the passwords by hashing them.

You can assign the value MD5 or SHA1 to this attribute to use one of these hashing algorithms. If you need to generate hash values for the passwords, you can take advantage of a utility function of the FormsAuthentication class—one of the longest named methods in the .NET Framework—named HashPasswordForStoringInConfigFile().

Storing Usernames and Passwords in a Database Table

If you need to maintain a large number of usernames and passwords, storing them in the Web.Config file quickly becomes unmanageable. A better choice is to store user credentials in a database table.

In this section, we’ll configure our application to use Forms Authentication with a database table. We will start over from scratch by creating the necessary database objects, a registration page, and a new login page.

Let’s start by creating the database objects. Perform the following steps to create the database table that will contain the usernames and passwords:

  1. In the Server Explorer window, expand the Data Connection to the Northwind database.

  2. Right-click Tables and select New Table.

  3. Enter the following table columns:

    Column Name

    Data Type

    Length

    Allow Nulls

    User_ID

    int

    4

    False

    User_Username

    Varchar

    20

    False

    User_Password

    Varchar

    20

    False

  4. Mark the User_ID column as an identity column by assigning the value True to its Identity property (look in the Property sheet at the bottom of the Table Editor).

  5. Click Save to save the table and name the new table UserList.

Next, we need to create a stored procedure that verifies username and passwords against the UserList table. We’ll name our stored procedure CheckPassword. It will return one of three possible values:

0—Username and password are valid

1—Password is invalid

2—Username is invalid

Do the following to create the stored procedure:

  1. Right-click the Stored Procedures folder under the Northwind Data Connection and select New Stored Procedure.

  2. Enter the following code for the new stored procedure:

    CREATE PROCEDURE dbo.CheckPassword
    (
      @username Varchar(20),
      @password Varchar(20)
    )
    AS
    /*
    Check for valid Username and Password
    */
    If Exists
    (
    Select User_ID From UserList
    Where User_Username = @Username
    And User_Password = @Password
    )
    Return 0
    
    /*
    Check for valid Username
    */
    
    If Exists
    (
    Select User_ID From UserList
    Where User_Username = @Username
    )
    Return 1
    
    /*
    Username doesn't exist
    */
    Return 2
    
  3. Click Save to save the CheckPassword stored procedure.

Next, we need to create the Web Form Page that we want to password protect.

  1. Add a new folder named Confidential by right-clicking your project name in the Solution Explorer Window and selecting Add, New Folder.

  2. Add a new Web Form Page to the Confidential folder by right-clicking it in the Solution Explorer window and selecting Add, Add Web Form. Provide the name TopSecret.aspx for the new Web Form Page and click Open.

  3. Drag a Flow Layout Panel from the HTML tab in the Toolbox onto the TopSecret.aspx page.

  4. Enter the text Ultra Security Clearance Required! in the Flow Layout Panel.

Next, we need to add the necessary Web.Config files to enable Forms Authentication and to password protect the Confidential folder.

  1. Modify the application root Web.Config file as follows:

    <configuration>
    <system.web>
      <authentication mode="Forms" />
    </system.web>
    </configuration>
    
  2. Add a new Web.Config file to the Confidential folder by right-clicking it in Solution Explorer, selecting Add, Add New Item, Web Configuration File, and clicking Open.

  3. Enter the following configuration settings for the new Web.Config file:

    <configuration>
    <system.web>
      <authorization>
        <deny users="?" />
      </authorization>
    </system.web>
    </configuration>
    

Finally, we need to create the Login.aspx page. (If a Login.aspx page already exists in your project, you can modify it.)

  1. Add a new Web Form Page to your project by right-clicking the name of your project in the Solution Explorer window and selecting Add, Add Web Form. Provide the name Login.aspx for the new Web Form Page and click Open.

  2. Drag a Label control from the Web Forms tab in the Toolbox onto the Designer surface. Clear the Text property of the Label control.

  3. Drag a TextBox control from the Web Forms tab in the Toolbox onto the Designer surface and assign the following values to its properties:

    Property

    Value

    ID

    txtUsername

  4. Drag a second TextBox control from the Web Forms tab in the Toolbox onto the Designer surface and assign the following values to its properties:

    Property

    Value

    ID

    txtPassword

    TextMode

    Password

  5. Drag two HTML labels from the HTML tab in the Toolbox onto the Designer surface. Enter the text Username for the first label and the text Password for the second label. Position the labels next to the TextBox controls.

  6. Drag a Button control from the Web Forms tab onto the Designer surface.

Next, you need to add the CheckPassword stored procedure to the Login.aspx page and create the Button_Click handler that calls the stored procedure:

  1. Drag the CheckPassword stored procedure from the Stored Procedures folder under the Data Connections folder in the Server Explorer window onto the Designer surface.

  2. Double-click the Button control. This will switch you to the Code Editor and add a Button_Click handler.

  3. Enter the following code for the Button1_Click handler:

    C#

    private void Button1_Click(object sender, System.EventArgs e)
    {
      int intResult = 0;
      sqlCommand1.Parameters[ "@username" ].Value = txtUsername.Text;
      sqlCommand1.Parameters[ "@password" ].Value = txtPassword.Text;
      sqlConnection1.Open();
      sqlCommand1.ExecuteNonQuery();
      intResult = (int)sqlCommand1.Parameters[ "@RETURN_VALUE" ].Value;
      sqlConnection1.Close();
    
      switch (intResult)
      {
      case 0:
        System.Web.Security.FormsAuthentication.RedirectFromLoginPage(
          txtUsername.Text, false );
        break;
      case 1:
        Label1.Text = "Invalid Password";
        break;
      case 2:
        Label1.Text = "Invalid Username";
        break;
      }
    }
    

    VB.NET

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    VB.NET Handles Button1.Click
      Dim intResult As Integer
    
      SqlCommand1.Parameters("@Username").Value = txtUsername.Text
      SqlCommand1.Parameters("@Password").Value = txtPassword.Text
      SqlConnection1.Open()
      SqlCommand1.ExecuteNonQuery()
      intResult = SqlCommand1.Parameters("@RETURN_VALUE").Value
      SqlConnection1.Close()
    
      Select Case intResult
      Case 0
        System.Web.Security.FormsAuthentication.RedirectFromLoginPage( txtUsername.Text, False)
      Case 1
        Label1.Text = "Invalid Password"
      Case 2
        Label1.Text = "Invalid Username"
      End Select
    End Sub
    
  4. Right-click the TopSecret.aspx page (not the Login.aspx page) in the Solution Explorer window and select Build and Browse.

The Login.aspx page calls the CheckPassword stored procedure to verify the username and password entered into the form. If the username and password combination is valid, the user is redirected to the original page requested; otherwise, an appropriate error message is displayed in a Label control.

You can test the Login.aspx page by entering one or more usernames and passwords into the UserList table. Double-click the UserList table in the Server Explorer window and enter the usernames and passwords directly into the grid. Alternatively, you can add the Register.aspx page to your project as discussed in the next section to your project.

Adding a Registration Page

One of the primary advantages of using Forms Authentication with a database table is that it makes it easy to create a registration form. To enable users to register at your Web site, they only need to complete a form that adds their usernames and passwords to the appropriate database table.

In this section, we’ll extend the database application that we created in the previous section with a registration form (see Figure 16.3).

The registration form.

Figure 16.3. The registration form.

First, we need to create the stored procedure that adds a new user to the UserList table.

  1. Right-click the Stored Procedures folder under the Northwind Data Connection in the Server Explorer window and select New Stored Procedure.

  2. Enter the following code for the new stored procedure:

    CREATE PROCEDURE dbo.AddUser
    (
      @Username Varchar( 20 ),
      @Password Varchar( 20 )
    )
    AS
    If Exists
    (
      Select User_ID From UserList
      Where User_Username = @Username
    )
    Return 1
    
    Insert UserList
    (
      User_Username,
      User_Password
    )
    Values
    (
      @Username,
      @Password
    )
    
  3. Click Save.

Next, we need to add a link to the Login.aspx page to the Register.aspx page.

  1. Open the Login.aspx page by double-clicking the page in the Solution Explorer window.

  2. Add a HyperLink control to the page by dragging the control from under the Web Forms tab in the Toolbox onto the Designer surface.

  3. Assign the value New users click here to register! to the HyperLink control’s Text property.

  4. Double-click the Designer surface to switch to the Code Editor.

  5. Enter the following Page_Load handler:

    C#

    private void Page_Load(object sender, System.EventArgs e)
    {
    if (!Page.IsPostBack)
      HyperLink1.NavigateUrl =
        String.Format(
          "Register.aspx?ReturnURL={0}",
          Server.UrlEncode( Request.QueryString[ "ReturnURL" ] ) );
    }
    

    VB.NET

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
    VB.NET MyBase.Load
      If Not Page.IsPostBack Then
        HyperLink1.NavigateUrl = String.Format("Register.aspx?ReturnURL={0}",  Server
    VB.NET.UrlEncode(Request.QueryString("ReturnURL")))
      End If
    End Sub
    

Perform the following steps to create the Register.aspx page and add the necessary controls to the page:

  1. Add a new Web Form Page to your project named Register.aspx.

  2. Add a TextBox control to the Web Form Page and assign the following values to its properties:

    Property

    Value

    ID

    txtUsername

  3. Add a second TextBox control to the Web Form Page and assign the following values to its properties:

    Property

    Value

    ID

    txtPassword

    TextMode

    Password

  4. Add a third TextBox control to the Web Form Page and assign the following values to its properties:

    Property

    Value

    ID

    txtPassword2

    TextMode

    Password

  5. Add three HTML Label elements to the Web Form Page. Enter the text Username, Password, and Password Again into the labels and position them appropriately on the page.

  6. Add a RequiredFieldValidator control to the page. Assign the following values to the control’s properties:

    Property

    Value

    ControlToValidate

    txtUsername

    Text

    Required!

  7. Add a second RequiredFieldValidator control to the page. Assign the following values to the control’s properties:

    Property

    Value

    ControlToValidate

    txtPassword

    Text

    Required!

  8. Add a CompareValidator control to the page. Assign the following values to the control’s properties:

    Property

    Value

    ControlToValidate

    txtPassword

    ControlToCompare

    txtPassword2

    Text

    Passwords must match!

  9. Add a Label control to the Designer surface.

  10. Add a Button control to the Designer surface.

Next, you need to add the application logic to the page that adds the new username and password to the database table.

  1. Drag the AddUser stored procedure from the Server Explorer window onto the Register.aspx page.

  2. Double-click the Button control. This will switch you to the Code Editor and add a Button1_Click handler.

  3. Enter the following code for the Button1_Click handler:

    C#

    private void Button1_Click(object sender, System.EventArgs e)
    {
      int intResult = 0;
    
      sqlCommand1.Parameters[ "@Username" ].Value = txtUsername.Text;
      sqlCommand1.Parameters[ "@Password" ].Value = txtPassword.Text;
      sqlConnection1.Open();
      sqlCommand1.ExecuteNonQuery();
      intResult = (int)sqlCommand1.Parameters[ "@RETURN_VALUE" ].Value;
      sqlConnection1.Close();
    
      if (intResult == 0)
        System.Web.Security.FormsAuthentication.RedirectFromLoginPage(
          txtUsername.Text, false );
      else
        Label1.Text = "Username already taken!";
    }
    

    VB.NET

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    VB.NET Handles Button1.Click
      Dim intResult As Integer
    
      SqlCommand1.Parameters("@Username").Value = txtUsername.Text
      SqlCommand1.Parameters("@Password").Value = txtPassword.Text
      SqlConnection1.Open()
      SqlCommand1.ExecuteNonQuery()
      intResult = SqlCommand1.Parameters("@RETURN_VALUE").Value
      SqlConnection1.Close()
    
      If intResult = 0 Then
        System.Web.Security.FormsAuthentication.RedirectFromLoginPage( txtUsername.Text, False)
      Else
        Label1.Text = "Username already taken!"
      End If
    End Sub
    
  4. Right-click the TopSecret.aspx page in the Solution Explorer window and select Build and Browse.

When you build and browse the TopSecret.aspx page, you’ll be redirected to the Login.aspx page. If you click the New Users Click Here to Register! link, the Register.aspx page opens.

The Register.aspx page prevents you from entering a username that already exists in the UserList table. If you enter a new username and password, the username and password will be added to the database, and you will be automatically redirected to the TopSecret.aspx page.

Implementing Custom Roles with Forms Authentication

Custom roles enable you to apply security settings to groups of users. For example, instead of explicitly denying access to a page to Jane and Bob, you can add Jane and Bob to a custom role named Guests and deny access to all members of that role.

You can create custom roles when configuring Forms Authentication such as Administrators, Supervisors, and Moderators roles. The roles do not need to correspond to Windows groups. You can make up any set of roles that you want.

After you create the custom roles, you can refer to them in the Web.Config file to control access to pages in a folder. For example, you can specify that only Administrators have the right to access the pages in a particular folder.

In this section, we’ll modify the application that we created in the previous section to associate different roles with different users.

First, we need to add an additional column to the UserList database table that we’ll use to represent the roles associated with a user:

  1. Right-click the UserList table in the Server Explorer window and select Design Table.

  2. Add a new column named User_Roles. Assign the data type varchar and the length 500 to the column.

  3. Click the Save UserList button to save the changes to the UserList table.

Next, we need to create a new stored procedure to retrieve the roles for a user:

  1. Under the Northwind Data Connection, right-click Stored Procedures and select New Stored Procedure.

  2. Enter the following code for the stored procedure:

    CREATE PROCEDURE dbo.GetRoles
    (
      @Username Varchar(20)
    )
    AS
    SELECT User_Roles
    FROM UserList
    WHERE User_Username = @Username
    
  3. Save the new stored procedure by clicking the Save button.

Next, we need to modify the Global.asax file to associate the proper roles with a user.

  1. Open the Global.asax file by double-clicking it in the Solution Explorer window.

  2. Drag the GetRoles stored procedure from the Server Explorer window onto the Designer surface. This will add a new SqlConnection and a SqlCommand object to the page.

  3. Double-click the Designer surface to switch to the Code Editor and enter the following code for the Application_AuthenticateRequest() method:

    C#

    protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
      HttpContext Context = HttpContext.Current;
      string[] arrUserRoles = null;
    
      // Only assign roles if user is authenticated
      if (!Request.IsAuthenticated)
        return;
    
      // Get the roles for the user from the database
      sqlCommand1.Parameters[ "@Username" ].Value = User.Identity.Name;
      sqlConnection1.Open();
      arrUserRoles = ((string)sqlCommand1.ExecuteScalar()).Split(','),
      sqlConnection1.Close();
    
      // Assign the roles to the user
      Context.User =
        new System.Security.Principal.GenericPrincipal(Context.User.Identity, arrUserRoles);
    }
    

    VB.NET

    Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
      Dim arrUserRoles As String()
    
      ' Only assign roles if user is authenticated
      If Not Request.IsAuthenticated Then Return
    
    
      ' Get the roles for the user from the database
      SqlCommand1.Parameters("@Username").Value = User.Identity.Name
      SqlConnection1.Open()
      arrUserRoles = SqlCommand1.ExecuteScalar().Split(",")
      SqlConnection1.Close()
      ' Assign the roles to the user
      HttpContext.Current.User = New System.Security.Principal.GenericPrincipal( Context.User
    VB.NET.Identity, arrUserRoles)
    End Sub
    

Finally, we need to modify the authorization Web.Config file to allow only users in the Administrators role access to pages. Modify the Web.Config file in the Confidential folder as follows:

<configuration>
<system.web>
  <authorization>
      <allow roles="Administrators" />
     <deny users="*" />
  </authorization>
</system.web>
</configuration>

This Web.Config file allows members of the Administrators role access to pages but denies access to everyone else.

You can test the custom roles by assigning a comma-delimited list of roles to the User_Roles column in the UserList table. For example, if you assign the string Administrators,Operators to the User_Roles column, that user will be associated with both the Administrators and Operators roles.

Summary

In this chapter, you learned how to password protect pages in your application by taking advantage of Forms Authentication. You learned how to configure both authentication and authorization for Forms Authentication by using the Web.Config file.

You discovered how to store usernames and passwords in two places—the Web.Config file and a database table. Finally, you tackled an advanced feature of Forms Authentication; You created an application that makes use of custom user roles.

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

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