Article Options
Recently Viewed
Premium Sponsor
Premium Sponsor

 »  Home  »  Data Programming  »  XML  »  Form Authentication in ASP.NET using XML
 »  Home  »  Web Development  »  Form Authentication in ASP.NET using XML
 »  Home  »  Web Development  »  ASP.NET  »  Form Authentication in ASP.NET using XML
Form Authentication in ASP.NET using XML
by Guest Author | Published  10/12/2002 | XML Web Development ASP.NET | Rating:
Guest Author
This author account is for guest publications only, and does not reflect the bio for any particular author. 

View all articles by Guest Author...
Form Authentication in ASP.NET using XML

Guest Author: Pang Tat Sean

In ASP.NET, most of the tedious work of writing authentication form has been taken out. When user logs in using form authentication, a cookie is created and used to track the user throughout the site. Once user successfully logs in, you can issue an authentication cookie to save authenticated users from having to login every time they visit new page of your website. The cookie will expire when browser is closed.

Since many examples on the Internet for Form Authentication hover around use either database or web.config to store user maes and passwords, I have decided to write an example of how to create ASP.NET Authentication form using XML file for storing user information instead of Microsoft SQL Server or Microsoft Access database. I use the 'Code Behind' approach to separate the presentation layer from the logic layer and make the code more reusable. However, this is just a simple example and sure if want to use it in your own projects, there are some things here and there you need to change/add.

Web.config

<configuration>
     <System.web>
          <authentication mode="Forms">
               <forms name=".ASPXFORMSTEST"
                      loginUrl="login.aspx"
                      protection="All"
                      path="/" timeout="30" />
          </authentication>
          <authorization>
               <deny users="?" />
               <allow users="*" />
          </authorization>
     </System.web>
</configuration>

Users.xml

<?xml version="1.0"?>
<users>
  <pang>A15F69189FDD3C0A64F82C0AD73C319020351978</pang>
</users>

Default.aspx

<%@ Page Language="VB" %>
<script runat="server">

    ' Insert page code here


</script>
<html>
<head>
</head>
<body text="#000000" bgcolor="green">
    <form runat="server">
        <% response.write("Ya! You got the right password!!!"%>
    </form>
</body>
</html>

Login.aspx

<%@ Page Language="vb" Src="Login.vb" Inherits="UserLogin" %>
<script runat="server">

    Sub ProcessAdd(byval sender as Objectbyval e as EventArgs)
        response.redirect("AddLogin.aspx")
    End Sub

</script>
<html>
<head>
    <title>Custom Forms Authentication Login Form</title>
</head>
<body text="#000000" bgcolor="#ffffff">
    <form runat="server">
        <table cellspacing="0" cellpadding="0" width="400" border="0">
            <tbody>
                <tr>
                    <td>
                        Username : 
                    </td>
                    <td>
                        &nbsp;</td>
                    <td>
                        <asp:TextBox id="txtUser" 
                            runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        Password : 
                    </td>
                    <td>
                        &nbsp;</td>
                    <td>
                        <asp:TextBox id="txtPassword" runat="server" 
                            TextMode="Password">&#13;&#10;&#13;&#10;
                        </asp:TextBox>
                    </td>
                </tr>
                <tr>
                </tr>
                <tr>
                    <td>
                    </td>
                    <td>
                        &nbsp;</td>
                    <td>
                        <asp:CheckBox id="chkPersistLOgin" 
                            runat="server"></asp:CheckBox>
                        Remember my Credential
                    </td>
                </tr>
                <tr>
                    <td>
                        &nbsp;</td>
                    <td>
                        &nbsp;</td>
                    <td>
                        <asp:LinkButton id="lBAdd" onclick="ProcessAdd" 
                            runat="server" Text="Add User"></asp:LinkButton>
                    </td>
                </tr>
                <tr>
                    <td>
                        &nbsp;</td>
                    <td>
                        &nbsp;</td>
                    <td>
                        <br />
                        <asp:Button id="cmdLogin" onclick="ProcessLogin" 
                            runat="server" Text="Login"></asp:Button>
                    </td>
                </tr>
            </tbody>
        </table>
        <br />
        <br />
    </form>
    
    <asp:label id="ErrorMessage" runat="server"></asp:label>
</body>
</html>

Login.vb

Imports System
Imports System.Data.SqlClient
Imports System.Web.Security
Imports System.xml
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports Microsoft.VisualBasic

Public Class UserLogin
    Inherits System.Web.UI.Page
    
    Public txtUser as textbox
    Public txtPassword as textbox
    Public chkPersistLogin as CheckBox
    Public cmdLogin as Button
    Public ErrorMessage as label
  
  
    Public Sub ProcessLogin(objSender As ObjectobjArgs As EventArgs)
       ' This will return the full physical path of login.aspx
        Dim strCurrPath As String = Request.PhysicalPath
       ' In Order to get the full path of users.xml, we need to use [InStrRev] 

       ' function to replace the [login.aspx] with [users.xml] in order to get 
       ' the 
       ' full physical path for users.xml
        Dim strXMLDoc As String = Left(strCurrPath,InStrRev(strCurrPath_
            "\")) & "users.xml"
          
        Dim strUser As String = txtUser.Text
        Dim strPassword As String = txtPassword.Text
          
        ' hash the password by calling GetHashedPass function
        Dim strEncPassword As String = GetHashedPass(strPassword)
        Dim blnIsAuthenticated As Boolean
                   
        ' Create the XMLDocument
        Dim objXMLDoc As New XMLDocument()
        
        Errormessage.text = ""
    
        Try
            ' Load the XML Document
            objXMLDoc.Load(strXMLDoc)
        Catch err As Exception
            ErrorMessage.Text = "<b> The XML Document can not be " _
                & "loaded.</b>.<br>" & err.Message & "<br />" & err.Source
            Exit Sub
        End Try
            
        Dim nodeList As XmlNodeList

        ' creates a [XmlDocument] object and uses the [GetElementsByTagName] 
        ' method and the resulting [XmlNodeList] to display the password
        ' and verify it with the password entered by user
        
        nodeList = objXMLdoc.GetElementsByTagName(strUser)
    
          'see if we found an element with this username
        If Not nodeList Is Nothing Then
              Dim blnUserExists As Boolean = True
              Dim strUserCheck As String
              Try
                  strUserCheck = nodeList(0).FirstChild().Value
              Catch objError As Exception
                  ErrorMessage.Text = "<b>Invalid username</b> please " _
                      & "re-enter..."
                  blnUserExists = False
              End Try
              If blnUserExists = True Then
                  If strEncPassword = nodeList(0).FirstChild().Value Then
                      blnIsAuthenticated = True
                  Else
                      ErrorMessage.TExt = "<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
    
    Public Function GetHashedPass(ByVal aPassword As StringAs String
         ' Using [FormsAuthentication.HashPasswordForStoringInConfigFile] 
         ' method
         ' to hash the password .
         ' First parameter : the password to hash 
         ' Second parameter : password format(algorithms) ; either are "sha1" 
         ' or "md5"
          Return FormsAuthentication.HashPasswordForStoringInConfigFile_
              aPassword,"sha1")
    End Function

End Class
Generated using PrettyCode.Encoder

AddLogin.aspx

<%@ Page Language="vb" Src="AddUser.vb" Inherits="AddUser" %>
<html>
<head>
    <title>Custom Forms Authentication Login Form</title>
</head>
<body text="#000000" bgcolor="#ffffff">
    <form runat="server">
        <table cellspacing="0" cellpadding="0" width="400" border="0">
            <tbody>
                <tr>
                    <td>
                        Username : 
                    </td>
                    <td>
                        &nbsp;</td>
                    <td>
                        <asp:TextBox id="txtUser" 
                            runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        Password : 
                    </td>
                    <td>
                        &nbsp;</td>
                    <td>
                        <asp:TextBox id="txtPassword" runat="server" 
                            TextMode="Password">&#13;&#10;&#13;&#10;
                        </asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        &nbsp;</td>
                    <td>
                        &nbsp;</td>
                    <td>
                        <br />
                        <asp:Button id="cmdLogin" onclick="ProcessLogin" 
                            runat="server" Text="Add User"></asp:Button>
                    </td>
                </tr>
            </tbody>
        </table>
        <br />
        <br />
        <asp:label id="ErrorMessage" runat="server"></asp:label>
    </form>
</body>
</html>

AddUser.vb

Imports System
Imports System.Data.SqlClient
Imports System.Web.Security
Imports System.xml
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports Microsoft.VisualBasic

Public Class AddUser
    Inherits System.Web.UI.Page
    
    Public txtUser as textbox
    Public txtPassword as textbox
    Public cmdLogin as Button
    Public ErrorMessage as label

    Public Sub ProcessLogin(objSender As ObjectobjArgs As EventArgs)
        try
            Dim strEncPass As String
            Dim nextnode As XmlNode
            ' Create the [xmlDocument]
            Dim xmldoc As New System.Xml.XmlDocument()
            ' This will return the full physical path of AddLogin.aspx
            Dim strCurrPath As String = Request.PhysicalPath
            ' In Order to get the full path of users.xml, we need to use 
            ' [InStrRev] 
            ' function to replace the [AddLogin.aspx] with [users.xml] in 
            ' order to get the 
            ' full physical path for users.xml
            Dim strXMLDocPath As String = Left(strCurrPath,InStrRev_
                strCurrPath"\")) & "users.xml"
            
            ' Create an element 
            Dim elem As XmlElement = xmldoc.CreateElement(txtUser.Text)
            
            ' Using [FormsAuthentication.HashPasswordForStoringInConfigFile] 
            ' method
            ' to hash the password .
            ' First parameter : the password to hash 
            ' Second parameter : password format(algorithms) ; either are 
            ' "sha1" or "md5"
            strEncPass = _
                FormsAuthentication.HashPasswordForStoringInConfigFile_
                txtPassword.Text,"sha1")
            
            ' Load the xml document file
            xmldoc.Load(strXMLDocPath)
    
            ' get the nodes for [username]
            nextnode = xmldoc.LastChild
            
            ' set the [password] for the particular user
            elem.InnerText = strEncPass
            
            ' Append the [Username] and [password] to the xml document file
            nextnode.AppendChild(elem)
            
            ' Save the xml Document file
            xmldoc.Save(strXMLDocPath)
            
            ErrorMessage.text = " You have successfully add the new user!!!"
            
        Catch ex as Exception
            ErrorMessage.text = ex.message
        End Try
    End Sub
    
End Class
Generated using PrettyCode.Encoder
How would you rate the quality of this article?
1 2 3 4 5
Poor Excellent
Tell us why you rated this way (optional):

Article Rating
The average rating is: No-one else has rated this article yet.

Article rating:3.45652173913042 out of 5
 46 people have rated this page
Article Score33482
Comments    Submit Comment

Comment #1  (Posted by JRL on 01/23/2003)

Excellent article! This is a slick method and I plan on using it in the future.

One observation: it allows duplicate users to be added. It's a trivial fix, and the code for checking if a username exists in the XML file is in Login.vb, so there's an example of what's needed in AddUser.

All in all, great work!

JRL
 
Comment #2  (Posted by Dash on 03/28/2003)

this line is failing
xmldoc.Save(strXMLDocPath)

as it is show ing the error Access to the path "c:\inetpub\wwwroot\DotNetTest\users.xml" is denied

 
Comment #3  (Posted by Elad on 04/21/2003)

Did anyone succed to prevent adding duplicate users ?
I'm afraid it is not trivial fix for me ...

Thanks
 
Comment #4  (Posted by Pravesh on 05/26/2003)

Hi all,
It didn't fix up the problem for me as well.
Still not able to access the file "users.xml"
Any help will be appreciated.
Thankx
Pravesh
 
Comment #5  (Posted by Partha Roy on 05/27/2003)

Excellent aritcle for ASP.NET Programmer
 
Comment #6  (Posted by Wleon on 07/17/2003)

does anyone knows how to put security in ONLY one page, I need the rest of the site to be accessible by anyone without login, only the administration page needs security. Any ideas
 
Comment #7  (Posted by FSUPepDog on 07/18/2003)

For controlling access to one page, directory, part of site etc - check this document out

http://www.learnmobile.net/weblog/aspNET/FormsAuthenticationFAQs.html



 
Comment #8  (Posted by hjk on 03/21/2004)

hjk
 
Comment #9  (Posted by Mo on 04/28/2004)

Right click on Users.xml and select properties. Click on Security tab and grant Write access to Everyone.
 
Comment #10  (Posted by Bahram on 07/12/2004)

This is a very important and informative article and it's very efficiently presented. Thank you.
 
Comment #11  (Posted by an unknown user on 02/15/2005)
Rating
Very useful if it is in C# coding
 
Comment #12  (Posted by dotnetUser on 03/28/2005)
Rating
The User.xml denied access error is due to the fact that ASP.NET is trying to access the file not a regular user. ASP.Net actually has a user name called ASPNET and you can see it in Admin tools and look up Users and groups in Computer management in XP.
To fix this error goto a dos prompt then goto the directory that users.xml is in and type the following: cacls users.xml /e /g ASPNET:W
if you need to understand the switches just type cacls and hit enter for descriptions. The W will give write access. You should have to give it read access but if you do then retype the line and replace W with R.
 
Comment #13  (Posted by an unknown user on 05/04/2005)
Rating
This is not as efficient as the MSDN login example with XML file.
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconcookieauthenticationusinganxmlusersfile.asp

Stephen R.
 
Comment #14  (Posted by Miguel Espinosa on 05/11/2005)
Rating
What is de Password and User
TKS
 
Comment #15  (Posted by an unknown user on 09/28/2005)
Rating
Excellent work, nice article
 
Comment #16  (Posted by Dinesh on 12/07/2005)
Rating
It helped me to fix the problem as well.
 
Comment #17  (Posted by an unknown user on 01/19/2006)
Rating
it is a sincer help and very informative . thanks God bless you if i have any position i will consider you first
 
Comment #18  (Posted by an unknown user on 01/30/2006)
Rating
good example
 
Comment #19  (Posted by Hip on 02/16/2006)
Rating
Hi
Do not prompt how to adjust a font of the messages?
 
Comment #20  (Posted by Voron on 02/16/2006)
Rating
Good site. The guest book too good! Necessarily install to itself same.
 
Comment #21  (Posted by Andry on 02/16/2006)
Rating
Hi
More more of such sites.

Thanks
 
Comment #22  (Posted by an unknown user on 03/30/2006)
Rating
It helped me a lot.
 
Comment #23  (Posted by Rajesh on 03/30/2006)
Rating
I like it very much
 
Comment #24  (Posted by an unknown user on 03/30/2006)
Rating
It helped me a lot.
 
Comment #25  (Posted by an unknown user on 06/11/2006)
Rating
Article is really very good also the comments written to solve querries are also very good
 
Comment #26  (Posted by an unknown user on 08/03/2006)
Rating
you should really consider looking at the new provider model which is part of asp.net 2.0
 
Comment #27  (Posted by an unknown user on 08/16/2006)
Rating
Provider Model is good but it is still quite complicated to novice user, i hope MS can futher simply the works in future version of ASP.NET
 
Comment #28  (Posted by an unknown user on 10/26/2006)
Rating
Looks good but I put it all in Visual Studio Express and it finds errors, won't run it. I've been messing with it for 2 hours, hoping finally to have a way around the built-in SQL role verification, because SQL Express is behaving bizarrely and I desperately need to get a site up with secured access!
 
Comment #29  (Posted by Serge Baranovsky on 10/27/2006)
Rating
2unknown above:
Code in this artcle was written for Visual Studio 2003 - it may not work without modification in VS 2005
 
Comment #30  (Posted by boa_sovann on 03/17/2007)
Rating
why don't you use with some dbms like Sql Server etc.
that will be more excellent if you use with Sql Server and i hope you change the code to use with sql server.

thanks.

boa_sovann
 
Comment #31  (Posted by an unknown user on 04/29/2007)
Rating
Looks good and I wished that it was in C#..because Iam looking for that for ages.
 
Comment #32  (Posted by an unknown user on 05/19/2007)
Rating
gives answers to my different pblms
 
Comment #33  (Posted by an unknown user on 10/16/2007)
Rating
awesome article, I can almost win election now..my fellow australians
johnny howard
 
Comment #34  (Posted by an unknown user on 04/17/2008)
Rating
The Example is very difficult for new learner
 
Comment #35  (Posted by an unknown user on 02/09/2009)
Rating
Hi all. Treat all disasters as if they were trivialities but never treat a triviality as if it were a disaster.
I am from Vatican and too bad know English, give please true I wrote the following sentence: "Healthday news women who gain weight any time after the age of are more likely to develop breast."

THX :), Cal.
 
Comment #36  (Posted by an unknown user on 02/09/2009)
Rating
Could you help me. I've grown to realize the joy that comes from little victories is preferable to the fun that comes from ease and the pursuit of pleasure.
I am from Czech and also now am reading in English, please tell me right I wrote the following sentence: "Bill eilly teaches you how to vary your bet size against the working poor and proper seat selection."

Thanks for the help :), Lionel.
 
Comment #37  (Posted by an unknown user on 07/30/2009)
Rating
hi it'working but how to add user roles
please tell me anybady , my id ksmani_2006@yahoo.co.in
 
Sponsored Links