Using Forms Authentication in ASP.NET - Part 2
Posted on 2005-11-21 08:58 XXXCccddd 阅读(405) 评论(0) 编辑 收藏 举报The second portion of this article demonstrates how to implement your own authentication method using ASP.NET. Part 1 covered the basics of Forms Authentication and the concepts behind it (see http://www.15seconds.com/issue/020220.htm). This article assumes you have read part 1, or are familiar with the concepts of Forms Authentication.
Custom Forms Authentication Setup
Pages Used: Default.aspx, Login.aspx, Web.config, Users.xml, HashPassword.aspx
In this example of custom Forms Authentication, we will be using an XML document to store usernames and passwords.
- Create a folder named customForms under your webroot.
- Make this folder an application inside the Internet Services Manager. (This should be familiar territory if you have used the Global.asa in ASP.)
- Create a subfolder named unsecure.
- Create a document named HashPassword.aspx and move it to the unsecure directory.
Web.config Overview
The Web.config contains all the configuration settings for the Web application. I have highlighted the code that we will be examining. If any of the other code seems unfamiliar, please read part 1 of the article.
Web.config Code
<configuration> <system.web> <customErrors mode="Off"/> <authentication mode="Forms"> <forms name="AuthCookie" path="/" loginUrl="login.aspx" protection="All" timeout="10"> </forms> </authentication> <authorization> <deny users="?" /> </authorization> </system.web> <location path="unsecure"> <system.web> <authorization> <allow users="*"/> </authorization> </system.web> </location> </configuration>
Web.config Details
This example has added a new configuration section named location. This section allows us to override settings configured by the Web.config system.web configuration section. In this particular instance, we want to allow anonymous or unauthenticated users access to the unsecure directory. A common example of this would be having an entire Web application secured, except for a registration page. By allowing anonymous users access to the unsecured directory, we can place files viewable by anyone in this directory. You can create as many location sections as necessary.
Users.xml Overview
In this file we are storing all of our authentication data, such as username and passwords. The password is encrypted using the SHA1 algorithm, which I will explain later.
Users.xml Code
<?xml version="1.0"?> <users> <jeff>A94A8FE5CCB19BA61C4C0873D391E987982FBBD3</jeff> <mike>A94A8FE5CCB19BA61C4C0873D391E987982FBBD3</mike> </users>
Users.xml Details
Here we have a simple section called users that contains individual nodes for each user. In between the nodes, open and end tags we have a hashed password. Obviously this file could be redone to hold more values, such as first name, last name, or telephone number.
Login.aspx Overview
This page contains all the logic for authenticating a user. In this example we will authenticate to an XML file. You could easily put logic in this page for authenticating against a database as well.
Login.aspx Code
<%@Page Language="VB" %> <%@Import Namespace="System.Web.Security" %> <%@Import Namespace="System.Xml" %> <script language="VB" runat="server"> Sub ProcessLogin(objSender As Object, objArgs As EventArgs) Dim strCurrentPath As String = Request.PhysicalPath Dim strXMLDocPath As String = Left(strCurrentPath, InStrRev(strCurrentPath, "\")) & "users.xml" Dim strUser As String = txtUser.Text Dim strPassword As String = txtPassword.Text Dim strEncPassword As String = GetHashedPass(strPassword) Dim blnIsAuthenticated As Boolean Dim objXMLDoc As New XMLDocument() Try objXMLDoc.Load(strXMLDocPath) Catch objError As Exception ErrorMessage.innerHTML = "<b> The XML document could not be loaded.</b>.<br>" & _ objError.Message & "<br />" & objError.Source Exit Sub End Try Dim UserNodes As XmlNodeList UserNodes = objXMLDoc.GetElementsByTagName(strUser) 'see if we found an element with this username If Not UserNodes Is Nothing Then Dim blnUserExists As Boolean = True Dim strUserCheck As String Try strUserCheck = UserNodes(0).FirstChild().Value Catch objError As Exception ErrorMessage.InnerHtml = "<b>Invalid username</b> please re-enter..." blnUserExists = False End Try If blnUserExists = True Then If strEncPassword = UserNodes(0).FirstChild().Value Then blnIsAuthenticated = True Else ErrorMessage.InnerHtml = "<b>Invalid password</b> please re-enter..." End If End if End If If blnIsAuthenticated Then FormsAuthentication.RedirectFromLoginPage(strUser, chkPersistLogin.Checked) End If End Sub Function GetHashedPass(ByVal aPassword As String) As String Return FormsAuthentication.HashPasswordForStoringInConfigFile(aPassword,"sha1") End Function </script> <html> <head> <title>Custom Forms Authentication Login Form</title> </head> <body bgcolor="#FFFFFF" text="#000000"> <form runat="server"> <table width="400" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="80">Username : </td> <td width="10"> </td> <td><asp:TextBox Id="txtUser" runat="server"/></td> </tr> <tr> <td>Password : </td> <td width="10"> </td> <td><asp:TextBox Id="txtPassword" TextMode="Password" runat="server"/></td> </tr> <tr> <tr> <td></td> <td width="10"> </td> <td><asp:CheckBox id="chkPersistLogin" runat="server" />Remember my credentials <br> </td> </tr> <tr> <td> </td> <td width="10"> </td> <td><asp:Button Id="cmdLogin" OnClick="ProcessLogin" Text="Login" runat="server" /></td> </tr> </table> <br> <br> <div id="ErrorMessage" runat="server" /> </form> </body> </html>
Login.aspx Details
In this example I have added references for both System.Web.Security and System.Xml. We will be using classes from both of these namespaces. Here we create a procedure named ProcessLogin. Its purpose is to check the form data (username and password) against an XML file containing usernames and passwords.
First, we create some local variables for our text boxes and other information needed. We need to get the full path to the users.xml file, so we use Request.PhysicalPath and then we trim the script file name. We also create a variable to hold our hashed password.
Next, we wrap our XMLDoc.Load method call inside a Try...Catch statement. The Try...Catch statement is new to ASP and is a great way to handle errors and exceptions. In the next portion of our code, we dim a variable for our node list. We then assign it to a list of nodes from the XML document using the getElementsByTagName method. We check to see if the user exists; if they do, we verify that the hashed value they entered matches the hashed password in the XML document. If the user exists and the passwords match, then we set blnIsAuthenticated to true. At the end of the procedure, if blnIsAuthenticated = true, then we call the RedirectFromLoginPage method. Alternatively we could use the SetAuthCookie method to do the same thing, but without redirecting the user to another page.
Another function, GetHashedPassword, will be explained later. In the interface or HTML portion of the login.aspx file, we have 2 server-side text boxes, 1 server-side check box, and 1 button, also running server side. In the onClick event of the button we call the ProcessLogin procedure. We also have a div running server side that will display any errors to the user.
Default.aspx Overview
The code in this ASPX file is the same as the default.aspx in the first portion of this article.
Default.aspx Code
<%@Page Language="VB" %> <%@Import Namespace="System.Web.Security" %> <script language="vb" runat="server"> Sub SignOut(objSender As Object, objArgs As EventArgs) 'delete the users auth cookie and sign out FormsAuthentication.SignOut() 'redirect the user to their referring page Response.Redirect(Request.UrlReferrer.ToString()) End Sub Sub Page_Load() 'verify authentication If User.Identity.IsAuthenticated Then 'display Credential information displayCredentials.InnerHtml = "Current User : <b>" & User.Identity.Name & _ "</b><br><br>Authentication Used : <b>" & _ User.Identity.AuthenticationType & "</b>" Else 'Display Error Message displayCredentials.InnerHtml = "Sorry, you have not been authenticated." cmdSignOut.disabled = True End If End Sub </script> <html> <head> <title>Forms Authentication</title> </head> <body bgcolor="#FFFFFF" text="#000000"> <span class="Header">Forms Based Authentication using Custom Method</span> <br> <br> <div id="displayCredentials" runat="server" /> <br> <br> <form runat="server"> <input id="cmdSignOut" type="submit" Value="Sign Out" runat="server" onserverclick="SignOut" /><p /> </form> </body> </html>
Default.aspx Details
This page has the same functionality as the default.aspx in part 1. It simply displays the username and authentication method used.
HashPassword.aspx Overview
This page allows an unauthenticated user to create a hashed password. This can be used for storing passwords in the credentials section of the Web.config, inside an XML file, or in a database.
HashPassword.aspx Code
<%@Page Language="VB" %> <%@Import Namespace="System.Web.Security" %> <script language="VB" runat="server"> Sub GetHashedPass(objSender As Object, objArgs As EventArgs) Dim strEncPass As String strEncPass = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Value,"sha1") hashedPass.InnerHtml = "Hashed Password for Web.config, XML File or Database<br><b>" & _ strEncPass & "</b>" End Sub </script> <html> <head> <title>Create Hashed Password</title> </head> <body bgcolor="#FFFFFF" text="#000000"> <b>Create Hashed Password</b> <form runat="server"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td>Password to encrypt: <input id="txtPassword" type="password" runat="server" name="text"/> <input type="submit" value="Hash Pass" runat="server" onserverclick="GetHashedPass"/> </td> </tr> <tr> <tr> <td> </td> </tr> <tr> <td> <div id="hashedPass" runat="server"/> </td> </tr> </table> </form> </body> </html>
HashPassword.aspx Details
Again we need to import the System.Web.Security namespace for using the Forms Authentication namespace. Here we have a procedure that takes the text of our text box and hashes it using SHA1 hashing algorithm. The name of the method that does this is HashPasswordForStoringInConfigFile (quite possibly the longest method name I've ever seen). This method takes two parameters, the string to hash and the algorithm to be used. You can use either SHA1 or MD5 for hashing with this method. There are several other encryption options available in .NET (see Resources section below).
Resources
For more information on encryption options, see:
Cryptography namespace -- http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemsecuritycryptography.asp
Crypto example -- http://www.4guysfromrolla.com/webtech/090501-1.shtml
For more information on the SHA1 class and constructor, see:
Conclusion
As demonstrated, Forms Authentication is a powerful tool in developing Web applications. If you have any questions or comments regarding this series, please feel free to contact me.
About the Author
Jeff Gonzalez has been working in the IT industry for the last six years. He started his IT career as an NT4 administrator and network engineer. While working for a hosting company, he recognized the power of Windows DNA and sought out to learn everything he could about it. Since his foray into the Internet development world, he has worked on several e-commerce, e-business, and intranet applications. Jeff is currently working at Microsoft doing ASP.NET, VS.NET, and mobility controls support. He can be reached at rig444@hotmail.com.