Microsoft KB Archive/308157

= How To Implement Forms-Based Authentication in Your ASP.NET Application by Using Visual Basic .NET =

Article ID: 308157

Article Last Modified on 10/29/2007

-

APPLIES TO


 * Microsoft ASP.NET 1.1
 * Microsoft ASP.NET 1.0
 * Microsoft Visual Basic .NET 2003 Standard Edition
 * Microsoft Visual Basic .NET 2002 Standard Edition
 * Microsoft SQL Server 2000 Standard Edition
 * Microsoft SQL Server 7.0 Standard Edition

-



This article was previously published under Q308157



For a Microsoft Visual C# .NET version of this article, see 301240.

This article refers to the following Microsoft .NET Framework Class Library namespaces:
 * System.Data.SqlClient
 * System.Web.Security

IN THIS TASK
SUMMARY
 * Requirements
 * Create an ASP.NET Application Using Visual Basic .NET
 * Configure the Security Settings in the Web.config File
 * Create a Sample Database Table to Store Users Details
 * Create a Logon.aspx Page
 * Code the Event Handler So That It Validates the User Credentials
 * Create a Default.aspx Page
 * Troubleshooting

REFERENCES



SUMMARY
This article demonstrates how to implement forms-based authentication by using a database to store the users.

back to the top

Requirements
The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
 * Microsoft Visual Studio .NET
 * Microsoft SQL Server
 * Microsoft Internet Information Services (IIS) version 5.0 or later

back to the top

Create an ASP.NET Application Using Visual Basic .NET

 * 1) Open Visual Studio .NET.
 * 2) Create a new ASP.NET Web Application, and specify the name and location.

back to the top

Configure the Security Settings in the Web.config File
This section demonstrates how to add and modify the   and   configuration sections to configure the ASP.NET application to use forms-based authentication.  In Solution Explorer, open the Web.config file. Change the authentication mode to Forms.  Insert the  tag, and fill in the appropriate attributes. (For more information about these attributes, refer to the MSDN documentation or the QuickStart documentation that is listed in the REFERENCES section.) Copy the following code, and then click Paste as HTML on the Edit menu to paste the code in the   section of the file:     Deny access to the anonymous user in the   section as follows:   </li></ol>

back to the top

Create a Sample Database Table to Store Users Details
This section demonstrates how to create a sample database to store the user name, password, and role for the users. You need the role column if you want to store user roles in the database and implement role-based security. <ol> From the Windows Start menu, click Run, and then type notepad to open Notepad.</li>  Highlight the following SQL script code, right-click the code, and then click Copy. In Notepad, click Paste on the Edit menu to paste the following code: if exists (select * from sysobjects where id = object_id(N'[dbo].[Users]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[Users] GO CREATE TABLE [dbo].[Users] (   [uname] [varchar] (15) NOT NULL,    [Pwd] [varchar] (25) NOT NULL ,    [userRole] [varchar] (25) NOT NULL , ) ON [PRIMARY] GO ALTER TABLE [dbo].[Users] WITH NOCHECK ADD CONSTRAINT [PK_Users] PRIMARY KEY NONCLUSTERED (       [uname]    )  ON [PRIMARY] GO

INSERT INTO Users values('user1','user1','Manager') INSERT INTO Users values('user2','user2','Admin') INSERT INTO Users values('user3','user3','User') GO </li> Save the file as Users.sql.</li> On the Microsoft SQL Server computer, open Users.sql in Query Analyzer. From the list of databases, click pubs, and run the script. This creates a sample users table and populates the table in the Pubs database to be used with this sample application.</li></ol>

back to the top

Create a Logon.aspx Page
<ol> Add a new Web Form to the project named Logon.aspx.</li> Open the Logon.aspx page in the editor, and switch to HTML view.</li>  Copy the following code, and use the Paste as HTML option on the Edit menu to insert the code between the tags: <font face=&quot;Verdana&quot;>Logon Page <input type=&quot;submit&quot; Value=&quot;Logon&quot; runat=&quot;server&quot; ID=&quot;cmdLogin&quot;> <asp:Label id=&quot;lblMsg&quot; ForeColor=&quot;red&quot; Font-Name=&quot;Verdana&quot; Font-Size=&quot;10&quot; runat=&quot;server&quot; /> This Web Form is used to present a logon form to users so that they can provide their user name and password to log on to the application. </li> Switch to Design view, and save the page.</li></ol>

back to the top

Code the Event Handler So That It Validates the User Credentials
This section presents the code that is placed in the code-behind page (Logon.aspx.vb). <ol> Open the Logon.aspx.vb file.</li>  Import the required namespaces in the code-behind file: Imports System.Data.SqlClient Imports System.Web.Security </li>  Create a ValidateUser function to validate the user credentials by looking in the database. (Make sure that you change the Connection string to point to your database.) Private Function ValidateUser(ByVal userName As String, ByVal passWord As String) As Boolean Dim conn As SqlConnection Dim cmd As SqlCommand Dim lookupPassword As String

lookupPassword = Nothing

' Check for an invalid userName. ' userName must not be set to nothing and must be between one and 15 characters. If ((userName Is Nothing)) Then System.Diagnostics.Trace.WriteLine(&quot;[ValidateUser] Input validation of userName failed.&quot;) Return False End If       If ((userName.Length = 0) Or (userName.Length > 15)) Then System.Diagnostics.Trace.WriteLine(&quot;[ValidateUser] Input validation of userName failed.&quot;) Return False End If

' Check for invalid passWord. ' passWord must not be set to nothing and must be between one and 25 characters. If (passWord Is Nothing) Then System.Diagnostics.Trace.WriteLine(&quot;[ValidateUser] Input validation of passWord failed.&quot;) Return False End If       If ((passWord.Length = 0) Or (passWord.Length > 25)) Then System.Diagnostics.Trace.WriteLine(&quot;[ValidateUser] Input validation of passWord failed.&quot;) Return False End If

Try ' Consult with your SQL Server administrator for an appropriate connection ' string to use to connect to your local SQL Server. conn = New SqlConnection(&quot;server=localhost;Integrated Security=SSPI;database=pubs&quot;) conn.Open

' Create SqlCommand to select pwd field from the users table given a supplied userName. cmd = New SqlCommand(&quot;Select pwd from users where uname=@userName&quot;, conn) cmd.Parameters.Add(&quot;@userName&quot;, SqlDbType.VarChar, 25) cmd.Parameters(&quot;@userName&quot;).Value = userName

' Execute command and fetch pwd field into lookupPassword string. lookupPassword = cmd.ExecuteScalar

' Cleanup command and connection objects. cmd.Dispose conn.Dispose Catch ex As Exception ' Add error handling here for debugging. ' This error message should not be sent back to the caller. System.Diagnostics.Trace.WriteLine(&quot;[ValidateUser] Exception &quot; & ex.Message) End Try

' If no password found, return false. If (lookupPassword Is Nothing) Then ' You could write failed login attempts here to the event log for additional security. Return False End If

' Compare lookupPassword and input passWord by using a case-sensitive comparison. Return (String.Compare(lookupPassword, passWord, False) = 0)

End Function </li> You can use one of two methods to generate the forms authentication cookie and redirect the user to an appropriate page in the cmdLogin_ServerClick event. Sample code is provided for both scenarios. Use either of them according to your requirement. <ul>  Call the RedirectFromLoginPage method to automatically generate the forms authentication cookie and redirect the user to an appropriate page in the cmdLogin_ServerClick event: Private Sub cmdLogin_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles cmdLogin.ServerClick If ValidateUser(txtUserName.Value,txtUserPass.value) Then FormsAuthentication.RedirectFromLoginPage(txtUserName.Value, _     chkPersistCookie.Checked) Else Response.Redirect(&quot;logon.aspx&quot;, True) End If End Sub </li>  Generate the authentication ticket, encrypt it, create a cookie, add it to the response, and redirect the user. This gives you more control in how you create the cookie. You can also include custom data along with the FormsAuthenticationTicket in this case. Private Sub cmdLogin_ServerClick(ByVal sender As Object, _  ByVal e As System.EventArgs) Handles cmdLogin.ServerClick If Validateuser(txtUserName.Value,txtUserPass.Value) Then Dim tkt As FormsAuthenticationTicket Dim cookiestr As String Dim ck As HttpCookie

tkt = New FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now, _ dateTime.Now.AddMinutes(30), chkPersistCookie.Checked, &quot;your custom data&quot;) cookiestr = FormsAuthentication.Encrypt(tkt) ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr) if (chkPersistCookie.Checked) then ck.Expires=tkt.Expiration ck.Path = FormsAuthentication.FormsCookiePath Response.Cookies.Add(ck)

Dim strRedirect As String strRedirect = Request(&quot;ReturnURL&quot;) If strRedirect <> &quot;&quot; Then Response.Redirect(strRedirect, True) Else strRedirect = &quot;default.aspx&quot; Response.Redirect(strRedirect, True) End If  Else Response.Redirect(&quot;logon.aspx&quot;, True) End If End Sub </li></ul> </li></ol>

back to the top

Create a Default.aspx Page
This section creates a test page to which users are redirected after they authenticate. If users browse to this page without first logging on to the application, they are redirected to the logon page. <ol> Rename the existing WebForm1.aspx page as Default.aspx, and open it in the editor.</li>  Switch to HTML view, and copy the following code between the tags: <input type=&quot;submit&quot; Value=&quot;SignOut&quot; runat=&quot;server&quot; id=&quot;cmdSignOut&quot;> This button is used to log off the forms authentication session. </li> <li>Switch to Design view, and save the page.</li> <li> Import the required namespaces in the code-behind file: Imports System.Web.Security </li> <li> Open the code-behind page (Default.aspx.vb), and copy the following code in the cmdSignOut_ServerClick event handler: Private Sub cmdSignOut_ServerClick(ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles cmdSignOut.ServerClick FormsAuthentication.SignOut Response.Redirect(&quot;logon.aspx&quot;, True) End Sub </li> <li>Save and compile the project. You can now use the application.</li></ol>

back to the top

Troubleshooting

 * You may want to store passwords securely in a database. You can use the FormsAuthentication class utility function named HashPasswordForStoringInConfigFile to encrypt the passwords before you store them in the database or configuration file.
 * You may want to store the SQL connection information in the configuration file (Web.config) so that you can easily modify it if necessary.
 * You may consider adding code to prevent hackers who try to use different combinations of passwords from logging on. For example, you can include logic that accepts only two or three logon attempts. If the user cannot log on in a certain number of attempts, you may want to set a flag in the database to not allow that user to log on until that user re-enables his or her account by visiting a different page or by calling your support line. In addition, you should add appropriate error handling wherever necessary.
 * Because the user is identified based on the authentication cookie, you may want to use Secure Sockets Layer (SSL) on this application so that no one can retrieve the authentication cookie and any other valuable information that is being transmitted.
 * Forms-based authentication requires that your client accept or enable cookies on their browser.
 * The timeout parameter of the   configuration section controls the interval at which the authentication cookie is regenerated. You can choose a value that provides better performance and security.
 * Certain intermediary proxies and caches on the Internet may cache Web server responses that contain Set-Cookie headers, which are then returned to a different user. Because forms-based authentication uses a cookie to authenticate users, this can cause users to accidentally (or intentionally) impersonate another user by receiving a cookie from an intermediary proxy or cache that was not originally intended for them.

back to the top

<div class="references_section">