February 24, 2021
Hot Topics:

Two Quick Ways to Perform ASP.NET Authentication

  • By Anand Narayanaswamy
  • Send Email »
  • More Articles »

Authenticating Users Using an XML File

Even though you can easily authenticate users by using a Web.Config file, it is not advisable for sites with a large number of users. It is also very difficult to implement an automated system that directly adds users to the Web.Config file. A Web developer should manually add new usernames and passwords to the file for each new user. To avoid this hassle, ASP.NET provides a facility for authenticating users using an XML file. For this purpose, you have to create both a Web.Config file (Listing 1.4) and an XML file (Listing 1.5):

Listing 1.4 Web.Config

<authentication mode = "Forms">
<deny users = "?"/>

Listing 1.5 pwd.xml




XML is a case-sensitive language.

The next step is to create an ASP.NET page. Because it has to check two credentials (username and password), you have to add two TextBox controls and a Button control to the form. Double-click the button control and add the code given in Listing 1.6:

Listing 1.6

If IsValid then
   If XMLAuthentication(txtUsername.Text,txtPassword.Text) Then
   End If
End If

Listing 1.6 passes the two control IDs as parameters to the XMLAuthentication method. This method will contain the real code to authenticate users from your XML file. Further, if the username and password match with that of the XML file, the user will be redirected to the developer.com home page. The source code for this method is given in Listing 1.7:

Listing 1.7

    Dim dstPwd as DataSet
    Dim dtblPwd as DataTable

    Dim users() as DataRow
    dstPwd = New DataSet()

    dtblPwd = dstPwd.Tables(0)
    users = dtblPwd.Select("name = '"& strUsername & "' ")

    if users.Length > 0 Then
    if users(0)("pwd") = strPwd Then
    Return True
    lblStatus.Text = "Invalid Password"
    End If
    lblStatus.Text = "Username does not exist"
    End If
    Return False
    End Function

In Listing 1.7, the XML file is loaded by using the built-in ReadXML() method, and the XMLAuthentication method checks both the username and password. The method displays the relevant messages in the label control.

Download Source Code

You can download the complete ASP.NET application by clicking here.

About the Author

Anand Narayanaswamy (Microsoft MVP) is a freelance writer for Developer.com and Codeguru.com. He works as an independent consultant and runs NetAns Technologies (http://www.netans.com), which provides low-cost domain registration and Web hosting services. He can be reached at ananddotnet@yahoo.co.in.

Page 2 of 2

This article was originally published on June 7, 2004

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date