Scott Hanselman

How to force all cookies to Secure under ASP.NET 1.1

February 10, 2007 Comment on this post [0] Posted in ASP.NET
Sponsored By

Just a quick tip here. Thanks to John Batdorf for bringing it up. In order to prevent Session Hijacking, when you've got a secure site, it's a good idea to mark your cookies as "secure," meaning that they can't be accessed over HTTP. This prevents folks from being issued cookies over HTTPS then switching to HTTP in order to access the cookie with sniffers or other evil.

There's a few ways to do this in ASP.NET 1.1, here's an easy one. Under 2.0 you can say requireSSL="true" as well and avoid this code altogether (see below). For 1.1, add a handler for End_Request to your Global.asax.

This chunk of code is multipurpose, so don't blindly copy-paste. Note that it code also sets the Forms Auth cookie and Session cookie to HttpOnly, but that's not required.  If you have JavaScript DOM code that accesses cookies, you won't want those marked HttpOnly.

protected override void Application_EndRequest(Object sender, EventArgs e) 
{
      string authCookie = System.Web.Security.FormsAuthentication.FormsCookieName;
      foreach (string sCookie in Response.Cookies) 
      {
            if (sCookie == authCookie || sCookie == "ASP.NET_SessionId")
            { 
                  if(System.Environment.Version.Major<2)
                  {
                        // Force HttpOnly to be added to the cookie header under 1.x
                        Response.Cookies[sCookie].Path += ";HttpOnly";
                  }
            }
            //Force all cookies to SSL regardless of web.config settings!
            Response.Cookies[sCookie].Secure = true;
      }
}

The check if we're running under 2.0 is to prevent doubling up on the HttpOnly attribute if code compiled under 1.1 is run under 2.0 and you've set  httpOnlyCookies to true.

<httpCookies httpOnlyCookies="true" requireSSL="true" domain="" />

If you're using older versions of IIS, make sure you have this hotfix (274149) to ensure that IIS respects your secure cookies, or better yet, don't serve traffic on port 80.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Hosting By
Hosted in an Azure App Service

Comments are closed.

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.