This article demonstrates how to implement forms-based authentication by using a database to store the users.
Create an ASP.NET Application Using C# .NET
- Open Visual Studio .NET.
- Create a new ASP.NET Web application, and specify the name and location.
Configure the Security Settings in the Web.config File
This section demonstrates how to add and modify the <authentication> and <authorization> configuration sections to configure the ASP.NET application to use forms-based authentication.
- In Solution Explorer, open the Web.config file.
- Change the authentication mode to Forms.
- Insert the <Forms> tag, and fill the appropriate attributes. Copy the following code, and then click Paste as HTML on the Edit menu to paste the code in the <authentication> section of the file:
- Deny access to the anonymous user in the <authorization> section as follows:
1: <authentication mode="Forms">
2: <forms name=".ASPXFORMSDEMO" loginUrl="logon.aspx"
3: protection="All" path="/" timeout="30" />
4: </authentication>
5:
1: <authorization>
2: <deny users ="?" />
3: <allow users = "*" />
4: </authorization>
Create a Logon.aspx Page
- Add a new Web Form to the project named Logon.aspx.
- Open the Logon.aspx page in the editor, and switch to HTML view.
- Copy the following code, and use the Paste as HTML option on the Edit menu to insert the code between the <form> tags:
- This Web Form is used to present a logon form to users so that they can provide their user name and password to log on to the application.
- Switch to Design view, and save the page.
1: <h3>
2: <font face="Verdana">Logon Page</font>
3: </h3>
4: <table>
5: <tr>
6: <td>Email:</td>
7: <td><input id="txtUserName" type="text" runat="server"></td>
8: <td><ASP:RequiredFieldValidator ControlToValidate="txtUserName"
9: Display="Static" ErrorMessage="*" runat="server"
10: ID="vUserName" /></td>
11: </tr>
12: <tr>
13: <td>Password:</td>
14: <td><input id="txtUserPass" type="password" runat="server"></td>
15: <td><ASP:RequiredFieldValidator ControlToValidate="txtUserPass"
16: Display="Static" ErrorMessage="*" runat="server"
17: ID="vUserPass" />
18: </td>
19: </tr>
20: <tr>
21: <td>Persistent Cookie:</td>
22: <td><ASP:CheckBox id="chkPersistCookie" runat="server" autopostback="false" /></td>
23: <td></td>
24: </tr>
25: </table>
26: <input type="submit" Value="Logon" runat="server" ID="cmdLogin"><p></p>
27: <asp:Label id="lblMsg" ForeColor="red" Font-Name="Verdana" Font-Size="10" runat="server" />
28:
Code the Event Handler So That It Validates the User Credentials
This section presents the code that is placed in the code-behind page (Logon.aspx.cs).
- Double-click Logon to open the Logon.aspx.cs file.
- Import the required namespaces in the code-behind file:
- Create a ValidateUser function to validate the user credentials by looking in the database. (Make sure that you change the Connection string to point to your database).
- You can use one of two methods to generate the forms authentication cookie and redirect the user to an appropriate page in the cmdLogin_ServerClick event. Sample code is provided for both scenarios. Use either of them according to your requirement.
- Call the RedirectFromLoginPage method to automatically generate the forms authentication cookie and redirect the user to an appropriate page in the cmdLogin_ServerClick event:
- Generate the authentication ticket, encrypt it, create a cookie, add it to the response, and redirect the user. This gives you more control in how you create the cookie. You can also include custom data along with the FormsAuthenticationTicket in this case.
- Make sure that the following code is added to the InitializeComponent method in the code that the Web Form Designer generates:
1: using System.Data.SqlClient;
2: using System.Web.Security;
1: private bool ValidateUser( string userName, string passWord )
2: {
3: SqlConnection conn;
4: SqlCommand cmd;
5: string lookupPassword = null;
6:
7: // Check for invalid userName.
8: // userName must not be null and must be between 1 and 15 characters.
9: if ( ( null == userName ) || ( 0 == userName.Length ) || ( userName.Length > 15 ) )
10: {
11: System.Diagnostics.Trace.WriteLine( "[ValidateUser] Input validation of userName failed." );
12: return false;
13: }
14:
15: // Check for invalid passWord.
16: // passWord must not be null and must be between 1 and 25 characters.
17: if ( ( null == passWord ) || ( 0 == passWord.Length ) || ( passWord.Length > 25 ) )
18: {
19: System.Diagnostics.Trace.WriteLine( "[ValidateUser] Input validation of passWord failed." );
20: return false;
21: }
22:
23: try
24: {
25: // Consult with your SQL Server administrator for an appropriate connection
26: // string to use to connect to your local SQL Server.
27: conn = new SqlConnection( "server=localhost;Integrated Security=SSPI;database=pubs" );
28: conn.Open();
29:
30: // Create SqlCommand to select pwd field from users table given supplied userName.
31: cmd = new SqlCommand( "Select pwd from users where uname=@userName", conn );
32: cmd.Parameters.Add( "@userName", SqlDbType.VarChar, 25 );
33: cmd.Parameters["@userName"].Value = userName;
34:
35: // Execute command and fetch pwd field into lookupPassword string.
36: lookupPassword = (string) cmd.ExecuteScalar();
37:
38: // Cleanup command and connection objects.
39: cmd.Dispose();
40: conn.Dispose();
41: }
42: catch ( Exception ex )
43: {
44: // Add error handling here for debugging.
45: // This error message should not be sent back to the caller.
46: System.Diagnostics.Trace.WriteLine( "[ValidateUser] Exception " + ex.Message );
47: }
48:
49: // If no password found, return false.
50: if ( null == lookupPassword )
51: {
52: // You could write failed login attempts here to event log for additional security.
53: return false;
54: }
55:
56: // Compare lookupPassword and input passWord, using a case-sensitive comparison.
57: return ( 0 == string.Compare( lookupPassword, passWord, false ) );
58:
59: }
1: private void cmdLogin_ServerClick(object sender, System.EventArgs e)
2: {
3: if (ValidateUser(txtUserName.Value,txtUserPass.Value) )
4: FormsAuthentication.RedirectFromLoginPage(txtUserName.Value,
5: chkPersistCookie.Checked);
6: else
7: Response.Redirect("logon.aspx", true);
8: }
1: private void cmdLogin_ServerClick(object sender, System.EventArgs e)
2: {
3: if (ValidateUser(txtUserName.Value,txtUserPass.Value) )
4: {
5: FormsAuthenticationTicket tkt;
6: string cookiestr;
7: HttpCookie ck;
8: tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
9: DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data");
10: cookiestr = FormsAuthentication.Encrypt(tkt);
11: ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
12: if (chkPersistCookie.Checked)
13: ck.Expires=tkt.Expiration;
14: ck.Path = FormsAuthentication.FormsCookiePath;
15: Response.Cookies.Add(ck);
16:
17: string strRedirect;
18: strRedirect = Request["ReturnUrl"];
19: if (strRedirect==null)
20: strRedirect = "default.aspx";
21: Response.Redirect(strRedirect, true);
22: }
23: else
24: Response.Redirect("logon.aspx", true);
25: }
1: this.cmdLogin.ServerClick += new System.EventHandler(this.cmdLogin_ServerClick);
Create a Default.aspx Page
This section creates a test page to which users are redirected after they authenticate. If users browse to this page without first logging on to the application, they are redirected to the logon page.
- Rename the existing WebForm1.aspx page as Default.aspx, and open it in the editor.
- Switch to HTML view, and copy the following code between the <form> tags:
- This button is used to log off the forms authentication session.
- Switch to Design view, and save the page.
- Import the required namespaces in the code-behind file:
- Double-click SignOut to open the code-behind page (Default.aspx.cs), and copy the following code in the cmdSignOut_ServerClick event handler:
- Make sure that the following code is added to the InitializeComponent method in the code that the Web Form Designer generates:
- Save and compile the project. You can now use the application.
1: <input type="submit" Value="SignOut" runat="server" id="cmdSignOut">
1: using System.Web.Security;
1: private void cmdSignOut_ServerClick(object sender, System.EventArgs e)
2: {
3: FormsAuthentication.SignOut();
4: Response.Redirect("logon.aspx", true);
5: }
1: this.cmdSignOut.ServerClick += new System.EventHandler(this.cmdSignOut_ServerClick);