BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News Forms Authentication Extensions

Forms Authentication Extensions

This item in japanese

Normally we bring your large and complex frameworks that, even if you could build on your own, you probably wouldn’t want to. But sometimes a simple little library with just a couple of classes can make all the difference. One such example is a project called FormsAuthenticationExtensions.

Even with modern frameworks such as MVC 3, the venerable Forms Authentication is still the recommended security model for public facing web sites. When combined with membership and role providers is it easy to configure and yet also still incredibly flexible. In its simplest mode, Forms Authentication is based on an encrypted cookie that contains the username or id. Any other user information must be accessed in another fashion. Options include:

  • Calling Membership.GetUser, which makes a round-trip to the database when using the default implementation. While certainly doable, it can be tricky to get right and its location in the page lifecycle makes debugging difficult.
  • Storing the extra information in Session, which means you actually have to have session state turned on. This is no problem for small sites, but can be a real problem once you start needing multiple web servers.

FormsAuthenticationExtensions offers a third option. Instead of building a membership cache or setting up a session server you can simply store extra bits of information right in the authentication cookie. Here is an example from a small MVC project I used to test the library. This replaces the default code in the AccountController.LogOn method.

  

//FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);

var ticketData = new NameValueCollection();
ticketData["Name"] = model.UserName; ticketData["Key"] = membershipUser.ProviderUserKey.ToString(); ticketData["Email"] = membershipUser.Email;

new FormsAuthentication().SetAuthCookie(model.UserName, model.RememberMe, ticketData);

A word of warning from the project’s founder:

Size always matters.

The information you store this way is embedded in the forms ticket, which is then encrypted and sent back to the users browser. On every single request after this, that entire cookie gets sent back up the wire and decrypted. Storing any significant amount of data here is obviously going to be an issue. Keep it to absolutely no more than a few simple values.

With no dependencies to speak of, enabling FormsAuthenticationExtensions is as simple as loading the NuGet package and changing a couple lines of code.

If you have any other small but useful libraries that you think people should know about please tell us about them by commenting here or by using the “Contribute News” link at the top of the page.

Rate this Article

Adoption
Style

BT