Welcome Guest!
Create Account | Login
Locator+ Code:

Search:
FTPOnline Channels Conferences Resources Hot Topics Partner Sites Magazines About FTP RSS 2.0 Feed

Free Trial Issue of Visual Studio Magazine

Drill Down on Authentication (Continued)

It's also important to include the Page.IsValid condition at the beginning of this procedure. By default, validation controls use JavaScript for client-side validation. When calling Page.Validate(), the validation takes place on the server. This is important for browsers that either have JavaScript turned off or don't support it. If you don't include this part, validation doesn't occur if the browser doesn't support JavaScript or doesn't have JavaScript enabled. This means you should always include server-side validation in your code.

The FormsAuthentication class provides two methods that you use in this example. The Authenticate() method checks the specified user name and password against those stored in the web.config file and returns a Boolean value indicating whether a match was found. Remember that the methods of FormsAuthentication are static, so you don't need to create an instance of FormsAuthentication to use them—you simply access them through the name of the class:

if (FormsAuthentication.Authenticate(UsernameText.Text, 
PasswordText.Text))

If you find a match for the supplied credentials, you can use the RedirectFromLoginPage() method:

FormsAuthentication.RedirectFromLoginPage(
UsernameText.Text, false);
ADVERTISEMENT

This method performs several tasks at once. It creates an authentication ticket for the user; it encrypts the information from the authentication ticket; it creates a cookie to persist the encrypted ticket information; it adds the cookie to the HTTP response, sending it to the client; and it redirects the user to the originally requested page (which is contained in the query string parameter of the login page request's URL).

Implement a Persistent Cookie?
The second parameter of RedirectFromLoginPage() indicates whether a persistent cookie should be created. You store persistent cookies on the user's hard drive, enabling you to reuse them during later visits. Finally, if Authenticate() returns false, an error message is displayed on the page.

Logging a user out of forms authentication is as simple as calling the FormsAuthentication.SignOut() method:

protected void SignOutAction_Click(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();
}

You remove the authentication cookie when you call the SignOut() method. Depending on the application, you might want to redirect the user to another page when the user logs out. If the user requests another restricted page, the request will be redirected to the login page. You can also redirect to the login page immediately after calling the sign-out method. Or, you can use the Response.Redirect method.

Forms authentication includes the possibility of storing the password in different formats. In the <credentials /> configuration section, you specify the format of the password with the passwordFormat attribute, which has three valid values: Clear, where you store passwords as clear text in the <user /> elements of the <credentials /> section; MD5, where you store the hashed version of the password in the <user /> elements, as well as the when the algorithm used to hash the password is the MD5 algorithm; and SHA1, where the <user /> elements in the <credentials /> section of the web.config file contain the hashed password, as well as when the algorithm used to hash the password is the SHA1 algorithm.

When using the hashed version of the passwords, you must write a tool or some code that hashes the passwords for you and stores the passwords in the web.config file. For storing the password, you should then use the FormsAuthentication.HashForStoringInConfigFile method instead of passing in the clear-text password:

string hashedPwd = 
FormsAuthentication.HashForStoringInConfigFile(
clearTextPassword, "SHA1");

The first parameter specifies the clear-text password, and the second one specifies the hash algorithm you should use. The result of the method call is the hashed version of the password.

If you want to modify users stored in web.config, you must use the configuration API of the .NET Framework. You cannot edit this section with the Web-based configuration tool. This code snippet modifies the section through the configuration API:

'Configuration MyConfig = 
WebConfigurationManager.OpenWebConfiguration(
        "~/");

ConfigurationSectionGroup SystemWeb = 
MyConfig.SectionGroups["system.web"];
AuthenticationSection AuthSec =
(AuthenticationSection)SystemWeb.Sections[
"authentication"];
AuthSec.Forms.Credentials.Users.Add(
new FormsAuthenticationUser(UserText.Text, PasswordText.Text));
MyConfig.Save();

Of course, you should allow only privileged users such as Web site administrators to execute the previous code, and the process executing the code must have write access to your web.config file. Also, you shouldn't include this sort of code in the Web application, but in an administration application only.

This should give you a good start for working with forms authentication. You've learned how to implement authentication systems that simplify coding and provide a great deal of flexibility. The online version of this article also delves into taking advantage of cookieless forms authentication, which ASP.NET 2.0 supports out of the box.

About the Authors
Matthew MacDonald is an author, educator, and MSCD developer. He is a regular writer for developer journals such as Inside Visual Basic, ASPToday, and Hardcore Visual Studio .NET. He's also the author several books, including Pro ASP.NET 2.0 in C# 2005, from which this chapter has been excerpted and modified.

Mario Szpuszta is working in the Developer and Platform Group of Microsoft Austria. He performs workshops, trainings, and proof-of-concept projects together with independent software vendors in Austria based on .NET, Web Services, and Office 2003 technologies.

Back to top














Java Pro | Visual Studio Magazine | Windows Server System Magazine
.NET Magazine | Enterprise Architect | XML & Web Services Magazine
VSLive! | Thunder Lizard Events | Discussions | Newsletters | FTP Home