asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search








Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

Using Forms Authentication in ASP.NET - Part 2
By Jeff Gonzalez
Rating: 4.0 out of 5
Rate this article


  • email this article to a colleague
  • suggest an article

    Introduction

    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:

    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemSecurityCryptographySHA1ClassTopic.asp

    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemSecurityCryptographySHA1ClassctorTopic.asp

    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.

  • Rate This Article
    Not HelpfulMost Helpful
    1 2 3 4 5
    Supporting Products/Tools
    AspEncrypt
    Built around the Microsoft CryptoAPI, AspEncrypt helps you harness all major encryption and hashing algorithms such as DES, Triple-DES, RC2, RC4, RSA, MD5 and SHA1 in just a few lines of code. The component can be used in tandem with AspEmail to send encrypted and signed mail in the industry-standard S/MIME format, or with AspUpload to encrypt files as they are being uploaded. AspEncrypt can also be used to issue and manage X.509 digital certificates.
    [Top]
    AspPDF
    AspPDF is an ASP/ASP.NET component which enables generation and management of documents in PDF format. Features include advanced text formatting, font embedding, form fill-in, images, tables, content and page extraction, document stitching, encryption, digital signatures, and more.
    [Top]
    Other Articles
    Feb 3, 2005 - ASP.NET Mixed Mode Authentication
    In many web applications it is desirable for both intranet users and external parties to be able to seamlessly log onto the system. The problem this raises is that it is not easy to allow intranet users to log in via Windows integrated authentication while also allowing external parties to log in to the same application using standard forms authentication. This article will show you one way to achieve the best of both worlds when it comes to authentication.
    [Read This Article]  [Top]
    Dec 8, 2004 - Designing Role-Based Security Models for .NET
    In this article, Michele Leroux Bustamante discusses authentication, authorization and role-based security in .NET. Along the way, he provides some best practices for implementing role-based security in some typical .NET application scenarios including rich clients, Web applications, and Web services.
    [Read This Article]  [Top]
    May 11, 2004 - SharePoint Security and .NET Impersonation
    When implementing custom components that require access to restricted resources, implicit impersonation must be used. Jay Nathan shows how to create a class that makes using .NET Impersonation a snap.
    [Read This Article]  [Top]
    Mar 10, 2004 - Intellectual Property Protection and Code Obfuscation
    Learn about the execution process of CLR-based programs and how to protect your applications from being easily disassembled back into source code.
    [Read This Article]  [Top]
    Feb 24, 2004 - How to Send Secure Mail in ASP-Based E-Commerce Applications - Part II
    Businesses that utilize encrypted e-mail may find Secure Multipurpose Internet Mail Extensions (S/MIME) to be somewhat restrictive. This article shows how to use security features in PDF as an alternative to S/MIME.
    [Read This Article]  [Top]
    Feb 2, 2004 - Fighting Spambots with .NET and AI
    Bill Gates, in a recent interview, predicted the end of spam by 2006. One of the methods he mentioned involved a challenge only a real live person could handle. Adnan Masood shows how to use AI and .NET to create a user verification scheme that incorporates similar concepts Gates alluded to.
    [Read This Article]  [Top]
    Jan 21, 2004 - Configuring .NET Code Access Security
    Code Access Security (CAS) is the .NET Framework security model that grants code permission to resources based on "evidence" pertaining to the encapsulating assembly. In this article, David Myers examines CAS and explains different configuration methods.
    [Read This Article]  [Top]
    Mar 10, 2003 - Platform Neutral and Transparent Encryption of Sensitive Customer Information
    Zhenlei Cai combines an open source C++ encryption library with SQL Server extended stored procedures to create a platform neutral, transparent encryption solution that resides at the database layer.
    [Read This Article]  [Top]
    Jan 15, 2003 - Exploring Machine.Config - User Security and More
    Christopher Spann offers a .NET configuration tip that should help ease system administrators' fears of security compromise and thus assuage growing developer demand for a .NET environment.
    [Read This Article]  [Top]
    Dec 10, 2002 - Encrypting Cookie Data with ASP.NET
    You don't have to be a cryptography expert or spend lots of money on third-party components to secure sensitive data in .NET. In this article, Wayne Plourde shows just how easy it is to encrypt cookie data using encryption classes in the .NET System.Security.Cryptography namespace.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry



    JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Solutions
    Whitepapers and eBooks
    Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Win Server ‘08
    HP eBook: Putting the Green into IT
    Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
    Avaya Article: Setting Up a SIP A/S Development Environment
    IBM Article: How Cool Is Your Data Center?
    Microsoft Article: Managing Virtual Machines with Microsoft System Center
    HP eBook: Storage Networking , Part 1
    Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Intel Video: Are Multi-core Processors Here to Stay?
    On-Demand Webcast: Five Virtualization Trends to Watch
    HP Video: Page Cost Calculator
    Intel Video: APIs for Parallel Programming
    HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
    Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Sun Download: Solaris 8 Migration Assistant
    Sybase Download: SQL Anywhere Developer Edition
    Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
    Red Gate Download: SQL Compare Pro 6
    Iron Speed Designer Application Generator
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
    eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
    IBM Article: Collaborating in the High-Performance Workplace
    HP Demo: StorageWorks EVA4400
    Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
    Microsoft How-to Article: Get Going with Silverlight and Windows Live
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES