October 20, 2002 - Forms-based Authentication | WebReference

October 20, 2002 - Forms-based Authentication

Yehuda Shiran October 20, 2002
Forms-based Authentication
Tips: October 2002

Yehuda Shiran, Ph.D.
Doc JavaScript

ASP.NET includes the built-in class FormsAuthentication that provides static methods to handle authentication. The class belongs to the System.Web.Security namespace and cannot be inherited. This class provides the capability of forms-based authentication, which is unique to ASP.NET and was not provided by ASP. There are two advantages to forms-based authentication. First, you can customize the login UI. Using the ASP.NET forms-based authentication you have full flexibility over what the authentication page looks like. You can add the site's look-and-feel, user-oriented Help, or links to registration pages. The second advantage is that you can check the username and password using your Store database, as opposed to requiring an NT account for each user.

In order to use authentication, you first need to define which pages need authentication. You accomplish this with the <authorization> tag in Web.config. In IBuySpy Store, we have three pages that need authorization: OrderList.aspx, OrderDetails.aspx, and CheckOut.aspx. Since a random user might be logged in to a temporary account, we can't let that user checkout items and pay, see the history of the orders, or examine the details of the orders. Here are the definitions of these three files in Web.config:

  <location path="Checkout.aspx">
    <system.web>
      <authorization>
        <deny users="?" />
      </authorization>
    </system.web>
  </location>
  <location path="OrderList.aspx">
    <system.web>
      <authorization>
        <deny users="?" />
      </authorization>
    </system.web>
  </location>
  <location path="OrderDetails.aspx">
    <system.web>
      <authorization>
        <deny users="?" />
	      </authorization>
    </system.web>
  </location>
You specify the login page in Web.config with the <authentication> tag:

  <system.web>
    <authentication mode="Forms">
      <forms name="IBuySpyStoreAuth" loginUrl="login.aspx" protection="All" path="/" />
    </authentication>
  </system.web>
One of the methods of FormsAuthentication is RedirectFromLoginPage(). It redirects an authenticated user back to the originally requested URL. Here is how we use this in IBuySpy's Login.aspx:

  FormsAuthentication.RedirectFromLoginPage(customerId, RememberLogin.Checked);
Another method is SetAuthCookie() which creates an authentication cookie with the user ID in it. We use in IBuySpy's Register.aspx:

  FormsAuthentication.SetAuthCookie(customerId, false);