Comments
Richard Davies wrote: The UK has a good crop of technology pioneers in cloud computing - for example ElasticHosts, FlexiScale, Flexiant, OnApp - and also some strong government initiatives such as G-Cloud. We will have to see whether this kind of technical leadership converts into swift mass-market adoption or not.
Cloud Computing
Conference & Expo
November 2-4, 2009 NYC
Register Today and SAVE !..
SYS-CON.TV
Today's Top SOA Links


Forms Authentication with a Twist of AJAX
A detour around redirects

Forms Authentication for ASP.NET is extremely powerful in that it lets you quickly add a layer of security to your Web site. While the simplicity of setup and implementation makes this form of authentication extremely attractive, usability can sometimes be downright ugly. The core functionality of Forms Authentication relies on redirects - first redirecting anonymous requests to the login page, and then redirecting back to the originally requested resource. Constant redirects not only annoy users, they can disrupt your page logic. Mixing in some AJAX with your Forms Authentication will quickly eliminate the need for most redirects, and the associated negative effects.

Let's start out by first examining the behavior of forms authentication by setting up a simple project. Setting up authentication is extremely easy using Visual Studio 2005. Start by creating a new Web site.

Next, from the Web site menu choose 'ASP.NET Configuration,' which will launch the configuration wizard. Use the Web Site Administration Tool to enable Forms Authentication, and add one or more users.

Also disable anonymous logins to force all unauthenticated requests to be directed first to your login page. If you're familiar with the Authentication section of the web.config file, you can also manually set up these same options. If you didn't install SqlExpress when you first installed Visual Studio 2005, you may need to run aspnet_regsql.exe to set up the membership and role providers to take advantage of the Login controls. A quick search for aspnet_regsql.exe on MSDN should give you ample documentation for running the utility. Once you've finished configuring the site, add a new WebForm to your site, and call it "login.aspx." After adding the login page, drop a Login control onto the form. The login control was added with Visual Studio 2005, and contains the fields commonly used in conjunction with Forms Authentication. The Login control will also automatically create an authentication token for users passing in the correct credentials.

To see forms authentication in action, browse to the default.aspx page. You'll notice that you're immediately redirected to login.aspx and only redirected to default.aspx after submitting the appropriate credentials. Though this behavior doesn't seem very disruptive in this particular scenario, it becomes a huge disruption when it occurs in the middle of a user's session. When a user logs in, he only remains logged in for a limited amount of time. The default timeout for forms authentication is 30 minutes. That means that after 30 minutes of inactivity, the user will have to log back in before proceeding. Unfortunately, a timeout of 30 minutes doesn't necessarily guarantee that the user won't be logged out before that time limit is reached. For example, if the asp.net worker process were to be restarted, all users will automatically be logged out. This is a special concern if you're running your site in a hosted environment, where you have no control over when the worker process is restarted. To see exactly what a user's experience might be, you'll have to wait for ASP.NET to log you out. To expedite this, you can set the authentication timeout to one minute. This can be done in the web.config by adding timeout="1" to the forms element:

    <authentication mode="Forms">
       <forms name="appNameAuth" path="/" loginUrl="login.aspx" protection="All" timeout="1">
       </forms>
    </authentication>

To see just how disruptive a mid-session login can be, let's set up a real-world example. Add a textbox and a button to the default.aspx page of your site, and view the updated page in your browser. After logging in, type a value into the textbox. Wait one minute for your login to expire, and click the button.

As if the redirects weren't annoying enough, notice that the value you typed into the texbox has disappeared. The problem is that the form submit never occurred, since you were redirected to the login page. The form submit is the only way to get data from the client to the server, so if it doesn't happen you risk losing data. It's obvious that this behavior is a usability nightmare. Data loss can be extremely frustrating to users, leading to a negative user experience, lost data, bug reports, and lots of headaches for everyone involved.

Behavior modification is in order, and for that we need look no further than our friend, the XmlHttpRequest. Using AJAX, we can detect when a user has been logged out and provide the ability to log the user back in without a resorting to a postback or a redirect. Since we'll be providing the login functionality without a redirect, the data loss issue demonstrated above will no longer be a concern.

The idea is pretty simple - before a form submit use an AJAX request to check whether the user is still logged in. In a case where the user has been logged out, resubmit the user's credentials to the login page before continuing with the form submission. Because no other activity should be occurring during a form submit, we can execute all requests synchronously - simplifying the code.

When you decide to use AJAX, browser compatibility should be kept in mind. To ensure cross-browser compatibility upfront design is more important than ever. Even if cross-browser compatibility isn't a requirement for you, I'd still recommend attempting to be as cross-browser compliant as possible as long as it doesn't put your deliverables at risk. In this case, we have to consider two compatibility concerns, the first of which is how to create the XmlHTTPRequest object. The core of AJAX functionality, the XmlHttpRequest is responsible for communicating between the client and the server. The code for creating the object isn't very complicated and can be found in Listing [ajaxlogin.js] in the function "getXmlHTTP." This function makes a perfect addition to your script libraries for reuse. The second browser compatibility concern when dealing with AJAX is formatting the response. There are generally two formats used, XML and JavaScrpit Object Notations (JSON). These formats are extremely similar in that they can be used to serialize object data into text. However, the actual formatting is very different for the two. Both formats have their advantages, with JSON being the preferred format for cross-browser compatibility. It's favored over XML because of the varying XML support or lack of it from one browser to the next. JSON strings use curly braces {} to represent an object, and name value pairs to represent properties or sub-objects. Names must be strings, but values can be strings, objects, or even functions.

With the general plan now in place, we can start implementing our AJAX Login enhancement. First we'll need to create a way to determine whether the user is currently logged in or not. We must be able to get this information on the client side, through JavaScript. We've already decided to use AJAX to do this, but we have to choose which page to use for the request. The login page is the perfect choice, since it's one of the only pages to permit anonymous requests even when forms authentication is enabled. Alternatively, you could choose another page, but you must ensure that the page is accessible to unauthenticated users otherwise once you've logged out you'd never be able to log back in. Since we're reusing the login page for our own purpose in this case, it's important to differentiate an AJAX request for login status from all the other requests for the login page. A special value can be used to differentiate these requests, and can be checked for in the Load event of the page. This special value will get added to the parameter string passed to the Send function of the XmlHttpRequest so that it becomes part of the Page's Request parameter collection. Figure 1 looks for "conifrmAuthenticated" as the indicator that the request was an AJAX call to check the login status.

   protected void Page_Load(object sender, EventArgs e)
   {
     if (this.Page.Request["confirmAuthenticated"]!=null)
     {
       Response.Clear();
       Response.Write("{\"isAuthenticated\":" +
       this.User.Identity.IsAuthenticated.ToString().ToLower() + "}");
       Response.End();
     }
   }


About Anthony Lombardo
Anthony Lombardo is the product manager of NetAdvantage for ASP.NET at Infragistics, Inc.  He is responsible for spearheading product management and strategies for Infragistics’ ASP.NET product line, working directly with the vice president of engineering to set the direction, plan, and manage product development. Prior to joining Infragistics, Anthony served as a Network Administrator for North Brunswick Board of Education and worked for Rutgers University in their technical support division. Since beginning his career with Infragistics in 2000, Anthony has been involved with every aspect of the development cycle, including playing a key role in the creation of the Presentation Layer Framework for ASP.NET, and determining the product feature set of NetAdvantage for ASP.NET.

 

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

It would be a good article if the source code was complete. Is there anyway to get a copy of the complete source code? The ajaxlogin.js is missing.

Good article, but your source code was incomplete; the zip didn't include the .js file which is where most of the functionality appears to be...

Forms Authentication with a Twist of AJAX article has some problems. Both the Figure 1 online link and the magazine article reference point to the VS2005 project setup dialog Figure. Worse, Listing 1 download does not include ajaxlogin.js. Where is this file? Also, what is a valid username and password for this site?

Forms Authentication for ASP.NET is extremely powerful in that it lets you quickly add a layer of security to your Web site. While the simplicity of setup and implementation makes this form of authentication extremely attractive, usability can sometimes be downright ugly. The core functionality of Forms Authentication relies on redirects - first redirecting anonymous requests to the login page, and then redirecting back to the originally requested resource. Constant redirects not only annoy users, they can disrupt your page logic. Mixing in some AJAX with your Forms Authentication will quickly eliminate the need for most redirects, and the associated negative effects.


Your Feedback
Rob wrote: It would be a good article if the source code was complete. Is there anyway to get a copy of the complete source code? The ajaxlogin.js is missing.
Paul wrote: Good article, but your source code was incomplete; the zip didn't include the .js file which is where most of the functionality appears to be...
Bob Baker wrote: Forms Authentication with a Twist of AJAX article has some problems. Both the Figure 1 online link and the magazine article reference point to the VS2005 project setup dialog Figure. Worse, Listing 1 download does not include ajaxlogin.js. Where is this file? Also, what is a valid username and password for this site?
j j wrote: Forms Authentication for ASP.NET is extremely powerful in that it lets you quickly add a layer of security to your Web site. While the simplicity of setup and implementation makes this form of authentication extremely attractive, usability can sometimes be downright ugly. The core functionality of Forms Authentication relies on redirects - first redirecting anonymous requests to the login page, and then redirecting back to the originally requested resource. Constant redirects not only annoy users, they can disrupt your page logic. Mixing in some AJAX with your Forms Authentication will quickly eliminate the need for most redirects, and the associated negative effects.
Subscribe to the World's Most Powerful Newsletters
Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021

SYS-CON Featured Whitepapers
ADS BY GOOGLE