Using Custom Authentication

You don't have to rely on Windows domain account information to authorize users. In fact, that's neither practical nor possible for Internet applications that may have thousands or hundreds of thousands of users. A much more common procedure is to provide an HTML-based username and password dialog and then permit or deny access based on the user-supplied values. To do this, you normally need to be able to look up the name and password information in a database or file.

Note In this example, you can log on only with the username admin and the password admin.

Note Before you start, open the CSharpASP Properties dialog using the Internet Services Manager application and make sure that Anonymous Access is enabled, Integrated Windows Authentication is disabled, and Basic Authentication is disabled.

The Web Form ch18-2.aspx displays a form containing Username and Password Text controls and a Log In button. The title bar over the form provides directions and feedback. When the user submits the form, the code simply compares the values of the txtUsername and txtPassword fields with admin. When the user successfully logs in, the code sets a Session variable named "authenticated" to true and displays the message User Authenticated.

The code uses the Session["authenticated"] variable value as a flag to determine what to do. After successfully being authenticated, the user no longer sees the form.

Figure 18.7 shows the initial form state.

Figure 18.7: Custom authentication form before successful authentication After authentication, the page returns a success message (see Figure 18.8).
Figure 18.8: Custom authentication form after successful authentication

Requesting the page again brings up the message User Already Authenticated. The Session ["authenticated"] variable serves as both evidence of the user's authentication state and a means to prevent the user from resubmitting the form. With the form controls hidden, the user cannot submit the form (see Figure 18.9).

Figure 18.9: Custom authentication form after attempting to authenticate more than once

Note that the code that displays the User Already Authenticated message uses embedded HTML to set the Label's Text property. In other words, the browser interprets the embedded HTML as markup. If you want a Label or other control to display markup instead—for example, to place the phrase Use a <b> tag to start displaying bold text, and a </b> tag to stop displaying bold text. into a Label—you need to use the Server.HTMLEncode method to encode the text or manually substitute the character entities &lt; and &gt; for the left and right angle brackets, respectively.

Listing 18.2 contains the full code for the Web Form ch18-2.aspx.

Listing 18.2: The Web Form ch18-2 Uses Custom Authentication (ch18-2.aspx.cs)

using System;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Web;

using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

namespace CSharpASP.ch18 { /// <summary>

/// Summary description for ch18 2. /// </summary>

public class ch18 2 : System.Web.UI.Page {

protected System.Web.UI.WebControls.Label lblTitle; protected System.Web.UI.WebControls.TextBox txtPassword; protected System.Web.UI.WebControls.Label lblPassword; protected System.Web.UI.WebControls.TextBox txtUserName; protected System.Web.UI.WebControls.Label lblBackground; protected System.Web.UI.WebControls.Label lblUsername; protected System.Web.UI.WebControls.Button btnLogin; protected System.Web.UI.HtmlControls.HtmlGenericControl divForm;

private void Page Load(object sender, System.EventArgs e) { if (Session["authenticated"] == null) { Session["authenticated"] = false; lblTitle.ForeColor = Color.Blue;

lblTitle.Text = "Enter your account information.";

this.FindControl("divForm").Visible = true;

else if ((bool)Session["authenticated"]) { lblTitle.ForeColor = Color.Green;

lblTitle.Text = "User " + "font color=\"red\"><i>" +

"Already " + "</i></font>" + "Authenticated"; this.FindControl("divForm").Visible = false;

#region Web Form Designer generated code override protected void OnInit(EventArgs e) { //

// CODEGEN: This call is required by the ASP.NET Web

InitializeComponent(); base.Onlnit(e);

/// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary>

private void InitializeComponent() { this.btnLogin.Click +=

new System.EventHandler(this.btnLogin Click); this.Load += new System.EventHandler(this.Page Load);

#endregion private void btnLogin Click(object sender, System.EventArgs e) {

if (!(bool)Session["authenticated"]) {

if (txtUserName.Text.ToLower().Trim() != "admin") { lblTitle.ForeColor = Color.Red; lblTitle.Text = "Invalid Username";

else if (txtPassword.Text.ToLower().Trim() != "admin")

lblTitle.ForeColor = Color.Red; lblTitle.Text = "Invalid Password";

lblTitle.ForeColor = Color.Green; lblTitle.Text = "User Authenticated"; Session["authenticated"] = true;

Obviously, in a real application, you would normally want to look up the username and password values in a database table, and you might provide a button for new users to create a username and password, depending on why you're authenticating users. For example, in an Internet application where you're using authentication only to set news link preferences, you would let new users register themselves. You can think of this type of authentication as identification, because you need only to identify users rather than truly authenticating them. In contrast, in an online banking application, you may not want to let users register themselves—you might set up your security so that only bank employees may register new users.

When an unauthenticated user requests a page that requires authentication, you would redirect him to your login page. After successfully authenticating, you would redirect him back to the initially requested page. For example, suppose the user launches a browser and immediately requests the page somePage.aspx. You want the somePage.aspx page to be accessible only to authenticated users. Therefore, upon receiving the request for somePage, you would check the Session ["authenticated"] variable value and, finding it to be false, you would redirect the user to the login page (ch18-2.aspx). After the user is authenticated successfully, you would redirect back to somePage.aspx.

Don't worry, I won't make you write that code. Instead, I'll show you in the next section how ASP.NET performs those tasks automatically.

Was this article helpful?

0 0

Post a comment