HttpOnly and ASP.NET

I saw the HttpOnly flag for cookies mentioned in several blogs recently. HttpOnly is a new flag that you can append to a cookie, which makes the cookie unavailable to client side script (e.g. ‘document.cookie’). Microsoft introduced that, and it seems that currently no other browser than IE6 SP1 supports this.

ASP.NET 1.1 has no built-in support for HttpOnly currently. You must append the flag manually to your cookies, e.g. to the forms authentication cookie:

public static void SetAuthCookie(string user, string[] roles)
{
  HttpContext context = HttpContext.Current;

  // create new authentication ticket
  FormsAuthenticationTicket ticket =
    new FormsAuthenticationTicket(
    1,
    user,
    DateTime.Now,
    DateTime.Now.AddMinutes(30),
    false,
    string.Join(“,”, roles));

    // encrypt the ticket
    string cookieval = FormsAuthentication.Encrypt(ticket);

    // create new cookie and set contents
    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName);
    cookie.Value = cookieval;

    // IE6 knows this flag – this means the cookie will not be available to script code (Anti XSS)
    cookie.Path = FormsAuthentication.FormsCookiePath + “; HttpOnly”;

    context.Response.Cookies.Add(cookie);
}

or you could wire up an EndRequest event listener, which makes sure no cookie leaves your app without being flagged.

private void OnEndRequest(object sender, EventArgs e)
{
  HttpContext context = HttpContext.Current;

  foreach (string sCookie in context.Response.Cookies)
  {
    context.Response.Cookies[sCookie].Path += “; HttpOnly”;
  }
}

Either way – be aware that this is no bullet-proof anti cross site scripting measure. it is just another piece in the puzzle to make your app more secure.

btw – ASP.NET 2.0 has a HttpOnly property on the HttpCookie class…

 

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s