Online Book Reader

Home Category

Programming Microsoft ASP.NET 4 - Dino Esposito [414]

By Root 5748 0

The layout of a login page is nearly the same—a couple of text boxes for the user name and password, a button to confirm, and perhaps a label to display error messages. However, you can make it as complex as needed and add as many graphics as appropriate. The user enters the credentials, typically in a case-sensitive way, and then clicks the button to log on. When the login page posts back, the following code runs:

void LogonUser(object sender, EventArgs e)

{

string user = userName.Text;

string pswd = passWord.Text;

// Custom authentication

bool bAuthenticated = AuthenticateUser(user, pswd);

if (bAuthenticated)

FormsAuthentication.RedirectFromLoginPage(user, false);

else

errorMsg.Text = "Sorry, yours seems not to be a valid account.";

}

The event handler retrieves the strings typed in the user name and password fields and calls into a local function named AuthenticateUser. The function verifies the supplied credentials and returns a Boolean value. If the user has been successfully authenticated, the code invokes the RedirectFromLoginPage static method on the FormsAuthentication class to inform the browser that it’s time to issue a new request to the original page.

The RedirectFromLoginPage method redirects an authenticated user back to the originally requested URL. It has two overloads with the following prototypes:

public static void RedirectFromLoginPage(string, bool);

public static void RedirectFromLoginPage(string, bool, string);

The first argument is the name of the user to store in the authentication ticket. The second argument is a Boolean value that denotes the duration of the cookie, if any, being created for the authentication ticket. If this argument is true, the cookie is given a duration that equals the number of minutes set by the timeout attribute (which is 30 minutes by default). In this way, you get a cookie that persists across browser sessions. Otherwise, your authentication cookie will last for the current session only. Finally, the third argument optionally specifies the cookie path.

Authenticating the User


The authenticating algorithm—that is, the code inside the AuthenticateUser method seen earlier—is entirely up to you. For example, you might want to check the credentials against a database or any other user-defined storage device. The following listing shows a (rather naïve) function that compares the user name and password against the firstname and lastname columns of the Northwind Employees table in SQL Server:

private bool AuthenticateUser(string username, string pswd)

{

// Performs authentication here

string connString = "...";

string cmdText = "SELECT COUNT(*) FROM employees " +

"WHERE firstname=@user AND lastname=@pswd";

int found = 0;

using(SqlConnection conn = new SqlConnection(connString))

{

SqlCommand cmd = new SqlCommand(cmdText, conn);

cmd.Parameters.Add("@user",

SqlDbType.NVarChar, 10).Value = username;

cmd.Parameters.Add("@pswd",

SqlDbType.NVarChar, 20).Value = pswd;

conn.Open();

found = (int)cmd.ExecuteScalar();

conn.Close();

}

return (found > 0);

}

The query is configured to return an integer that represents the number of rows in the table that match the specified user name and password. Notice the use of typed and sized parameters in the SQL command as a line of defense against possible injection of malicious code. Notice also that the SQL code just shown does not support strong passwords because the SQL = operator in the WHERE clause doesn’t perform case-sensitive comparisons. To make provisions for that, you should rewrite the command as follows:

SELECT COUNT(*) FROM employees WHERE

CAST(RTRIM(firstname) AS VarBinary)=CAST(RTRIM(@user) AS VarBinary)

AND

CAST(RTRIM(lastname) AS VarBinary)=CAST(RTRIM(@pswd) AS VarBinary)

The CAST operator converts the value into its binary representation, while the RTRIM operator removes trailing blanks. To capture the name of the currently logged-in user, a page should just use the following code block:

Welcome, <%= User.Identity.Name %>.

Signing Out


While an explicit sign-in

Return Main Page Previous Page Next Page

®Online Book Reader