Use the HttpOnly cookie option

From Guidance Share

Jump to: navigation, search

- J.D. Meier, Alex Mackman, Michael Dunner, Srinath Vasireddy, Ray Escamilla and Anandha Murukan

Internet Explorer 6 Service Pack 1 supports a new HttpOnly cookie attribute, which prevents client-side script from accessing the cookie from the document.cookie property. Instead, an empty string is returned. The cookie is still sent to the server whenever the user browses to a Web site in the current domain.

Note Web browsers that do not support the HttpOnly cookie attribute either ignore the cookie or ignore the attribute, which means it is still subject to XSS attacks.

The System.Net.Cookie class does not currently support an HttpOnly property. To add an HttpOnly attribute to the cookie, you need to use an ISAPI filter, or if you want a managed code solution, add the following code to your application's Application_EndRequest event handler in Global.asax:

protected void Application_EndRequest(Object sender, EventArgs e) 
{
 string authCookie = FormsAuthentication.FormsCookieName;
 foreach (string sCookie in Response.Cookies) 
 {
   // Just set the HttpOnly attribute on the Forms authentication cookie
   // Skip this check to set the attribute on all cookies in the collection
   if (sCookie.Equals(authCookie))
   { 
     // Force HttpOnly to be added to the cookie header
     Response.Cookies[sCookie].Path += ";HttpOnly";
   }
 }
}

Note ASP.NET 2.0 provides an HttpOnly property on the HttpCookie class, which you can directly set to true.

References

Personal tools