The most common type of authentication that you will want to implement with ASP.NET is forms-based cookie authentication. In this approach, we use a simple Web form combined with a modification to the Web.configfile to provide user authentication.
Let’s look at an example of using forms-based authentication to validate users against a database.
The first step is to create the Web.configfile as shown in the following example:
<?xml version=”1.0” encoding=”utf-8” ?> <configuration>
<system.Web>
<authentication mode=”Forms”>
<forms name=”CookieFormApplication” loginUrl=”login.aspx” /> </authentication>
<authorization> <deny users=”?” /> </authorization>
<sessionState mode=”InProc” cookieless=”false” timeout=”20”/> </system.Web>
</configuration>
In this example we are setting the authentication mode to use forms based authentica- tion, establishing that all non-authenticated users should be denied access and that users will be redirected to the login.aspxto obtain authentication.
We will use an xml file, users.xml, to validate the users during the login session. The following example shows the format of the xml file used to validate the users credentials.
<Users> <User> <UserEmail>[email protected]</UserEmail> <UserPassword>jsmith</UserPassword> </User> <User> <UserEmail>[email protected]</UserEmail> <UserPassword>bjohnson</UserPassword> </User> </Users>
Once you have created the users.xmlfile, populate it with some sample user name/ password pairs for testing. Next, you can create the login.aspxform. The login.aspx form will collect the user name and password of the user and then compare these values against the xml file. If they match, an authentication cookie will be sent to the user. Should the username not be found in the XML file then the user is redirected to another page that allows them to add a new username/password to the xml file. Listing 13-2 provides a sample of the login.aspx form.
Listing 13-2 Example of login.aspx using forms-based authentication
<%@ Import Namespace=”System.XML” %> <%@ Import Namespace=”System.IO” %> <%@ Import Namespace=”System.Web.Security “ %> <%@ Import Namespace=”System.Data.SqlClient” %> <%@ Import Namespace=”System.Data.OleDB” %> <%@ Import Namespace=”System.Data” %> <%@ Page Language=”vb” debug=”True”%> <HTML>
<HEAD>
<TITLE>Session 13 Cookie Authentication </TITLE> <SCRIPT LANGUAGE=”VB” RUNAT=”Server”>
Sub btnLogin_Click(ByVal Sender As Object, ByVal E As EventArgs) Select Case ValidateUserXML(txtusername.text,txtpassword.text)
Case “Success”
FormsAuthentication.RedirectFromLoginPage (txtusername.text, chkPersistForms.Checked)
Case “PasswordFailed”
lblMessage.Text = “Sorry your password verification for the user “ & txtusername.text &” failed.”
Case “NoSuchUser”
Response.Redirect(“adduser/adduser.aspx?username=” & txtusername.text) End Select
End Sub
Sub btnAddNewUser_Click(ByVal Sender As Object, ByVal E As EventArgs)
Response.Redirect(“adduser/adduser.aspx?username=Enter User Name”) End Sub
Function ValidateUserXML(ByVal username as String, ByVal password as String) as String Dim cmd as String
Continued
Listing 13-2 Continued
cmd = “UserEmail=’” & username & “‘“ Dim ds as New DataSet
Dim fs as new
FileStream(Server.MapPath(“users.xml”),FileMode.Open,FileAccess.Read) Dim reader as new StreamReader(fs)
Dim pass as string Dim user as string ds.ReadXml(reader) fs.Close()
Dim users as DataTable Users = ds.tables(0) Dim Matches() as DataRow Matches = Users.Select(cmd) If Matches.length >0 Then
Dim row as DataRow row = matches(0)
pass = row.item(“UserPassword”) user = row.item(“userEmail”) if pass = password then
Return “Success” else Return “PasswordFailed” end if Else Return “NoSuchUser” End If End Function </SCRIPT> </HEAD> <BODY>
<FORM ID=”WebForm1” METHOD=”postPOST” RUNAT=”server”> <P>
<STRONG>Session 13 Forms Authentication</STRONG> </P>
<P>
Please enter your username and password information below and then select the Login Button.
</P> <P>
<ASP:LABEL ID=”lblMessage” RUNAT=”SERVER”></ASP:LABEL> </P>
<P> Email
<ASP:TEXTBOX ID=”txtUserName” RUNAT=”SERVER” TOOLTIP=”Please enter your Username here”></ASP:TEXTBOX>
</P> <P>
Password
<ASP:TEXTBOX ID=”txtPassword” RUNAT=”SERVER” TEXTMODE=”Password” TOOLTIP=”Please enter your password here.”></ASP:TEXTBOX>
<P>
<ASP:CHECKBOX ID=”chkPersistForms” RUNAT=”SERVER” TEXT=”Select to Persist Cookies”></ASP:CHECKBOX>
</P> <P>
<ASP:BUTTON ID=”btnLogin” RUNAT=”SERVER” TEXT=”Login” ONCLICK=”btnLogin_Click”></ASP:BUTTON>
<ASP:BUTTON ID=”btnAddUser” RUNAT=”SERVER” TEXT=”Add New User” ONCLICK=”btnAddNewUser_Click”></ASP:BUTTON>
</P> </FORM> </BODY> </HTML>
The login form displays a login page to the user. When the user selects the Login button, the btnLogin_Click()method is called. btnLogin_Click()calls a function that compares the e-mail address entered to the e-mail field to the users.xmlfile. If a valid e-mail is found, then the password of the user is tested. Once a match is discovered, then the FormsAuthentication.RedirectFromLoginPage ()method is called to redirect the user back to the originally requested page or resource while also writing the authentication cookie to the browser.
To test this functionality out, create another file called default.aspx as shown below, establish a virtual directory for all of the above described files (default.aspx,
login.aspx, users.xml, Web.config) and browse to the default.aspxpage:
<%@ Page Language=”vb”%> <HEAD>
<SCRIPT Language = “VB” Runat=”Server”>
Sub btnLogout_Click(ByVal Sender As Object, ByVal E As EventArgs) FormsAuthentication.Signout Response.Redirect(“default.aspx”) End Sub </SCRIPT> <HTML> <BODY>
<H1> You successfully logged in and gained access</H1> <FORM Runat=”Server”>
<asp:Button id=btnLogout runat=”SERVER” Text=”LogOut” OnClick=”btnLogout_Click”> </asp:Button> </P> </FORM> </BODY> </HTML>
And that does it — you have tested the user name and password against an xml file, authenticated the user, and forwarded the user to the appropriate resource. When you com- pare this approach against a similar scenario in ASP 3.0, it is clear that ASP.NET is stream- lining these basic functions for the developer.