Microsoft KB Archive/299987

= How to use database and ASP sessions to implement ASP security =

Article ID: 299987

Article Last Modified on 6/16/2006

-

APPLIES TO


 * Microsoft Active Server Pages 4.0

-



This article was previously published under Q299987





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:

http://www.microsoft.com/technet/security/prodtech/IIS.mspx



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 (&quot;&quot;) 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 (&quot;&quot;).

Create a user database table
 Click Start, click Run, type notepad in the Open box, and then press ENTER to start Notepad.  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  On the File menu, click Save. In the File name box, type User.txt . 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. 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. 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.</li> 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.</li></ol>

Create and configure the virtual directory
<ol> In Windows Explorer, create a folder under the Web root. By default, the Web root is :\Inetpub\Wwwroot. Name the folder ASPSecureAPP.</li> Open the Internet Services Manager Microsoft Management Console (MMC).

Note In Windows NT 4.0, this MMC is named Internet Service Manager. <ul> 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.</li> To open Internet Service Manager on a computer that is running Windows NT 4.0, follow these steps: <ol style="list-style-type: lower-alpha;"> Click Start, point to Programs, point to Windows NT 4.0 Option Pack, and then click Microsoft Internet Information Server.</li> Click Internet Service Manager.</li></ol> </li></ul> </li> Expand Machine, and then expand Default Web Site. Right-click the ASPSecureAPP folder that you created in step 1, and then click Properties.</li> On the Directory tab in the Properties dialog box, click Create in the Application Settings section to mark the directory as an application.</li></ol>

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 = &quot;no-cache&quot; Response.AddHeader &quot;Pragma&quot;, &quot;no-cache&quot; Response.Expires = -1 %> <form action=&quot;Validate.asp&quot; method=&quot;post&quot;> <P> Login ID:&#xa0;&#xa0; <INPUT type=text id=UID  name=UID> Password:&#xa0;&#xa0;<input type=&quot;password&quot; id=&quot;passwd&quot; name=&quot;passwd&quot;> </P> <input type=&quot;submit&quot; value=&quot;Logon&quot; id=&quot;submit1&quot; name=&quot;submit1&quot;>

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 = &quot;no-cache&quot; Response.AddHeader &quot;Pragma&quot;, &quot;no-cache&quot; Response.Expires = -1

Dim userid Dim Pwd 'Assign the user ID to this variable. The user provides the user ID. userid= Request.Form(&quot;UID&quot;) '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 <> &quot;&quot; then pwd = Request.Form(&quot;passwd&quot;) 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 = &quot;Provider=SQLOLEDB.1;User ID= ;Password= ;Initial Catalog=pubs;&quot; & _ &quot;Network Library=dbmssocn;Data Source=servername&quot;

Set Cn = Server.CreateObject(&quot;ADODB.Connection&quot;) Cn.Open StrConnect Set Rs = Server.CreateObject(&quot;ADODB.Recordset&quot;) Rs.Open &quot;Select * from Users where uid='&quot; & userid & &quot;'&quot;,Cn 'Check to see whether this user ID exists in your database. If Not Rs.EOF then If strcomp( pwd, Rs.Fields(&quot;password&quot;).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(&quot;UID&quot;) = userid Response.Redirect &quot;Default.asp&quot; Response.End Else 'Password is incorrect. Redirect the user to the logon page. Response.Redirect &quot;Logon.asp&quot; 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 &quot;Register.asp&quot; Response.End End if Else Response.Redirect &quot;Logon.asp&quot; Response.End End 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 = &quot;no-cache&quot; Response.AddHeader &quot;Pragma&quot;, &quot;no-cache&quot; 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 pwd Dim userid

userid = Request.Form(&quot;uname&quot;) pwd = Request.Form(&quot;pwd&quot;)

If userid <> &quot;&quot; then If pwd <> &quot;&quot; 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 = &quot;Provider=SQLOLEDB.1;User ID= ;Password= ;&quot; & _ &quot;Initial Catalog=pubs;Network Library=dbmssocn;Data Source=servername&quot;

Set Cn = Server.CreateObject(&quot;ADODB.Connection&quot;) Cn.Open StrConnect Set Rs = Server.CreateObject(&quot;ADODB.Recordset&quot;) Rs.Open &quot;Select * from Users where uid='&quot; & userid & &quot;'&quot;,Cn,3 If Rs.RecordCount>0 then Response.Write &quot;The Username that you entered has already been taken by someone else.&quot; Response.Write &quot;Use a different Username.&quot; Set Rs = Nothing Set Cn = Nothing Else Dim records Cn.Execute &quot;INSERT INTO USERS1 (uid,password) VALUES&quot; & _ &quot;('&quot; & userid & &quot;','&quot; & pwd & &quot;')&quot;, records If records=1 then Response.Write &quot;You have been registered successfully.&quot; Set Rs = Nothing Set Cn = Nothing Session(&quot;UID&quot;)= userid Response.Redirect &quot;Default.asp&quot; Response.End Else Response.Write Err.Description Set Rs = Nothing Set Cn = Nothing Response.End End if       End if    Else Response.Write &quot;Password is empty. Could not register. Try again.&quot; End if End if %>

<script language=&quot;javascript&quot;> function callsubmit {

if (frm1.pwd.value==frm1.pwdc.value) { frm1.submit; } else { alert(&quot;Password does not match. Re-enter the password&quot;); }

} <form action=&quot;&quot; method=&quot;post&quot; id=frm1 name=frm1> <P> Login ID:&#xa0;&#xa0; <INPUT type=text id=uname  name=uname> Password:&#xa0;&#xa0;<input type=&quot;password&quot; id=&quot;pwd&quot; name=&quot;pwd&quot;> Confirm Password:&#xa0;&#xa0;<input type=&quot;password&quot; id=&quot;pwdc&quot; name=&quot;pwdc&quot;> </P> <input type=&quot;button&quot; value=&quot;Register&quot; id=&quot;submit1&quot; name=&quot;submit1&quot; onclick=javascript:callsubmit;>

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 = &quot;no-cache&quot; Response.AddHeader &quot;Pragma&quot;, &quot;no-cache&quot; Response.Expires = -1

'Set the session variable to an empty string and also destroy the session to make 'to complete the user session. Session(&quot;UID&quot;)=&quot;&quot; Session.Abandon Response.Redirect &quot;Logon.asp&quot; 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 = &quot;no-cache&quot; Response.AddHeader &quot;Pragma&quot;, &quot;no-cache&quot; Response.Expires = -1

if session(&quot;UID&quot;)=&quot;&quot; then Response.Redirect &quot;Logon.asp&quot; Response.End else Response.Write &quot;You are logged on as &quot; & session(&quot;UID&quot;) & &quot; &quot; end if %> <HTML> <BODY> <A HREF=&quot;Logoff.asp&quot;>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 = &quot;no-cache&quot; Response.AddHeader &quot;Pragma&quot;, &quot;no-cache&quot; Response.Expires = -1

if session(&quot;UID&quot;)=&quot;&quot; then Response.Redirect &quot;Logon.asp&quot; Response.End end 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.

<div class="references_section">