You are currently offline, waiting for your internet to reconnect

How to use database and ASP sessions to implement ASP security

This article was previously published under Q299987
Retired KB Content Disclaimer
This article was written about products for which Microsoft no longer offers support. Therefore, this article is offered "as is" and will no longer be updated.
Notice
We strongly recommend that all users upgrade to Microsoft Internet Information Services (IIS) version 6.0 running on Microsoft Windows Server 2003. IIS 6.0 significantly increases Web infrastructure security. For more information about IIS security-related topics, visit the following Microsoft Web site:
SUMMARY
This step-by-step article discusses how to implement forms-based security for Active Server Pages (ASP) applications. You can use this mechanism when your application is security enhanced or when you want to allow only authenticated users. You can also use this mechanism when the users are not part of your internal domain, such as Internet users. This sample uses a database to store the users' information and then validates the users against this database.

Prerequisites

  • Microsoft Windows NT 4.0 Workstation, Windows NT 4.0 Server, Microsoft Windows 2000 Professional, Windows 2000 Server, Windows 2000 Advanced Server, or Microsoft Windows Server 2003
  • Microsoft Internet Information Server (IIS) 4.0 for computers that are running Windows NT 4.0, Microsoft Internet Information Services (IIS) 5.0 for computers that are running Windows 2000, or Microsoft Internet Information Services (IIS) 6.0 for computers that are running Windows Server 2003
  • Microsoft SQL Server 6.5 or a later version of SQL Server

How to design this application

This section briefly outlines the steps that are required to implement forms-based security or custom security on your ASP Web application:
  1. Present a logon form to the user.
  2. Validate the user credentials against the user information that is stored in your user database.
  3. Create a session variable and set its value to the user ID.
  4. For every subsequent request that the user makes, confirm that the value of this session variable is not equal to an empty string ("") to confirm that the user has logged on.
  5. If the variable is empty, either the user is not a valid user or the user has logged off from the session. Redirect the user to the logon page if the variable is empty.
  6. If the log on fails because the user does not exist in your database, the user may not be registered at your site yet. Redirect the user to the Register.asp page so that the user can register at your site. When the user registers, those user details are added to the user database.
  7. Provide a link to the log off page on all the pages except the logon page so that the user can log off from the session. This page clears the session variable that is holding the user ID by assigning it an empty string ("").

Create a user database table

  1. Click Start, click Run, type notepad in the Open box, and then press ENTER to start Notepad.
  2. Highlight the following SQL script, right-click the script, and then click Copy. In Notepad, click Paste on the Edit menu.
    CREATE TABLE [Users] (	[uid] [varchar] (25) NOT NULL ,	[password] [varchar] (25) NOT NULL ,	CONSTRAINT [PK_Users] PRIMARY KEY  CLUSTERED 	(		[uid]	)  ON [PRIMARY] ) ON [PRIMARY]GO					
  3. On the File menu, click Save. In the File name box, type User.txt.
  4. Click Start, point to Programs, point to Microsoft SQL Server, and then click Query Analyzer. In the Connect to SQL Server dialog box, specify the name of the server that is running SQL Server, the user ID, and the password to connect to SQL Server.
  5. On the File menu, click Open. In the Open dialog box, click All Files (*.*) in the Files of type box. Click User.txt in the list, and then click Open.
  6. In the DB box on the toolbar, select the database in which you want to create this table. If you do not have a specific database for this purpose, click Pubs to create this table in the sample Pubs database.
  7. After you select the database, click Execute on the Query menu to run the query. This step creates a Users table in the selected database.

Create and configure the virtual directory

  1. In Windows Explorer, create a folder under the Web root. By default, the Web root is SystemDrive:\Inetpub\Wwwroot. Name the folder ASPSecureAPP.
  2. Open the Internet Services Manager Microsoft Management Console (MMC).

    Note In Windows NT 4.0, this MMC is named Internet Service Manager.
    • To open Internet Services Manager on a computer that is running Windows 2000 or Windows Server 2003, click Start, click Run, type inetmgr in the Open box, and then press ENTER.
    • To open Internet Service Manager on a computer that is running Windows NT 4.0, follow these steps:
      1. Click Start, point to Programs, point to Windows NT 4.0 Option Pack, and then click Microsoft Internet Information Server.
      2. Click Internet Service Manager.
  3. Expand Machine, and then expand Default Web Site. Right-click the ASPSecureAPP folder that you created in step 1, and then click Properties.
  4. On the Directory tab in the Properties dialog box, click Create in the Application Settings section to mark the directory as an application.

Create the sample pages

Note If you use Notepad to create these pages, make sure that you click All Files in the Save As Type box of the Save As dialog box when you save the files.
Logon.asp
This page lets users type their user name and password to access your site.

Copy the following code into a new ASP page. Save the file as Logon.asp in the ASPSecureAPP folder of the Inetpub\Wwwroot directory.
<%'The following three lines of code are used to make sure that this page is not cached on the client.Response.CacheControl = "no-cache"Response.AddHeader "Pragma", "no-cache"Response.Expires = -1%><html><body><form action="Validate.asp" method="post"><P>Login ID:&#xa0;&#xa0;  <INPUT type=text id=UID  name=UID> <br>Password:&#xa0;&#xa0;<input type="password" id="passwd" name="passwd"> </P><input type="submit" value="Logon" id="submit1" name="submit1"></form></body></html>				
Validate.asp
After the user provides his or her logon information to log on to your application, this page validates the user information and then redirects the user to the appropriate page.

Copy the following code into a new ASP page. Change the connect string parameters so that they contain valid values. The connect string parameters are the following:
  • User ID
  • Password
  • Initial Catalog
  • Data Source
Save the file as Validate.asp in the ASPSecureAPP folder of the Inetpub\Wwwroot directory.
<%Response.Buffer=true'The following three lines of code are used to make sure that this page is not cached on the client.Response.CacheControl = "no-cache"Response.AddHeader "Pragma", "no-cache"Response.Expires = -1Dim useridDim Pwd'Assign the user ID to this variable. The user provides the user ID.userid= Request.Form("UID")'Check whether userid is an empty string. If it is empty, redirect to Logon.asp.'If it is not empty, connect to the database, and validate the user.if userid <> "" then    pwd = Request.Form("passwd")	    Dim Cn    Dim Rs    Dim StrConnect'Specify the connection string to access the database.'Remember to change the following connection string parameters to reflect the correct values'for your SQL server.    StrConnect = "Provider=SQLOLEDB.1;User ID=<username>;Password=<strong password>;Initial Catalog=pubs;" & _    "Network Library=dbmssocn;Data Source=servername"    Set Cn = Server.CreateObject("ADODB.Connection")    Cn.Open StrConnect    Set Rs = Server.CreateObject("ADODB.Recordset")    Rs.Open "Select * from Users where uid='" & userid & "'",Cn'Check to see whether this user ID exists in your database.    If Not Rs.EOF then        If strcomp( pwd, Rs.Fields("password").value , 1) = 0 then'Password is correct. Set a session variable, and redirect the user to a Default.asp page'or the main page in your application.            Session("UID") = userid            Response.Redirect "Default.asp"            Response.End        Else'Password is incorrect. Redirect the user to the logon page.            Response.Redirect "Logon.asp"            Response.End        End if    Else'If the user is not in your database, point him or her to the Register.asp page'so that he or she can register at your Web site to access your application.        Response.Redirect "Register.asp"        Response.End    End ifElse    Response.Redirect "Logon.asp"    Response.EndEnd if%>				
Register.asp
This page lets users register their user ID and password to access your site.

Copy the following code into a new ASP page. Change the connect string parameters so that they contain valid values. The connect string parameters are the following:
  • User ID
  • Password
  • Initial Catalog
  • Data Source
Save the file as Register.asp in the ASPSecureAPP folder of the Inetpub\Wwwroot directory.
<%Response.Buffer=true'The following three lines of code are used to make sure that this page is not cached on the client.Response.CacheControl = "no-cache"Response.AddHeader "Pragma", "no-cache"Response.Expires = -1'Check whether user has submitted user name and password so that you can 'add that user to the users database and register him or her as a valid 'user to use this application.'This is just the minimal code that you need. You can customize this the way you want.Dim pwdDim useriduserid = Request.Form("uname")pwd = Request.Form("pwd")If userid <> "" then    If  pwd <> "" then        Dim Cn        Dim Rs        Dim StrConnect'Specify the connection string to access the database.'Remember to change the following connection string parameters to reflect the correct values'for your SQL server.        StrConnect = "Provider=SQLOLEDB.1;User ID=<username>;Password=<strong password>;" & _        "Initial Catalog=pubs;Network Library=dbmssocn;Data Source=servername"        Set Cn = Server.CreateObject("ADODB.Connection")        Cn.Open StrConnect        Set Rs = Server.CreateObject("ADODB.Recordset")        Rs.Open "Select * from Users where uid='" & userid & "'",Cn,3        If Rs.RecordCount>0 then            Response.Write "The Username that you entered has already been taken by someone else."            Response.Write "Use a different Username."            Set Rs = Nothing            Set Cn = Nothing        Else            Dim records            Cn.Execute "INSERT INTO USERS1 (uid,password) VALUES" & _            "('" & userid & "','" & pwd & "')" , records            If records=1 then                Response.Write "You have been registered successfully."                Set Rs = Nothing                Set Cn = Nothing                Session("UID")= userid                Response.Redirect "Default.asp"                Response.End 			            Else                Response.Write Err.Description                Set Rs = Nothing                Set Cn = Nothing                Response.End 			            End if        End if    Else    Response.Write "Password is empty. Could not register. Try again."    End ifEnd if%><html><head><script language="javascript">function callsubmit(){if (frm1.pwd.value==frm1.pwdc.value) {frm1.submit();}else{alert("Password does not match. Re-enter the password");}}</script></head><body><form action="" method="post" id=frm1 name=frm1><P>Login ID:&#xa0;&#xa0;  <INPUT type=text id=uname  name=uname> <br>Password:&#xa0;&#xa0;<input type="password" id="pwd" name="pwd"> <br>Confirm Password:&#xa0;&#xa0;<input type="password" id="pwdc" name="pwdc"> </P><input type="button" value="Register" id="submit1" name="submit1" onclick=javascript:callsubmit();></form></body></html>				
Logoff.asp
This page lets users log off.

Copy the following code into a new ASP page. Save the file as Logoff.asp in the ASPSecureAPP folder of the Inetpub\Wwwroot directory.
<%Response.Buffer=True'The following three lines of code are used to make sure that this page is not cached on the client.Response.CacheControl = "no-cache"Response.AddHeader "Pragma", "no-cache"Response.Expires = -1'Set the session variable to an empty string and also destroy the session to make'to complete the user session.Session("UID")=""Session.AbandonResponse.Redirect "Logon.asp"Response.End%>				
Default.asp
You can use this page to test the other pages that you have created.

Copy the following code into a new ASP page. Save the file as Default.asp in the ASPSecureAPP folder of the Inetpub\Wwwroot directory.
<%'The following three lines of code are used to make sure that this page is not cached on the client.Response.CacheControl = "no-cache"Response.AddHeader "Pragma", "no-cache"Response.Expires = -1if session("UID")="" then     Response.Redirect "Logon.asp"    Response.Endelse    Response.Write "You are logged on as " & session("UID") & "<br>"end if%><HTML><BODY><A HREF="Logoff.asp">Click here to log off</A><BODY></HTML>				

Add validation code to pages

The following code checks whether the user has already logged on to your Web site and has not logged off yet.

Copy this block of code into each of your security-enhanced ASP pages except the Logon.asp page and the Validate.asp page. Do not add this code to the Logon.asp page or to the Validate.asp page. Make sure that you paste this code at the top of each page so that this code appears first.
<%'The following three lines of code are used to make sure that this page is not cached on the client.Response.CacheControl = "no-cache"Response.AddHeader "Pragma", "no-cache"Response.Expires = -1if session("UID")="" then     Response.Redirect "Logon.asp"    Response.Endend if%>				

How this application works

Essentially, this application has two pages (Logon.asp and Register.asp) that anyone can view without supplying their credentials. To view the rest of the pages, a user must log on by using a valid user ID and password. Therefore, when a user directly browses to any page that requires logon information, the user is redirected to the Logon.asp page. The users must provide a valid user ID and password in the Logon.asp page. If the password is incorrect, the user can try to log on again.

If the user's user ID and password do not exist in your database, the user is redirected to the Register.asp page where the user can register to use your application. When the user registers at your Web site through the Register.asp page, that user's details are entered in the user database that you are using to validate the users.

Troubleshooting

  • Based on the requirements and how secure this application is, you can enable Secure Sockets Layer (SSL) encryption on Logon.asp to avoid transferring the user credentials in clear text.
  • These user accounts do not map to Windows accounts. Therefore, you cannot directly use your Windows accounts to log on to this application.
  • This security mechanism uses ASP Session-based information. Therefore, this mechanism does not work for users who do not have cookies enabled.
REFERENCES
For more information, click the following article numbers to view the articles in the Microsoft Knowledge Base:
172138 How to create a virtual directory in Internet Information Services (IIS)
282060 Resources for securing Internet Information Services
299970 How to use NTFS permissions to protect a Web Page running on IIS 4.0 or 5.0
Properties

Article ID: 299987 - Last Review: 06/16/2006 08:29:38 - Revision: 4.2

Microsoft Active Server Pages 4.0

  • kbaspobj kbdatabase kbhowtomaster kbsecurity KB299987
Feedback
050&did=1&t=">