Securing session cookies in asp.net

Securing session cookies by itsself is very straightforward. By adding the following markup to the system.web section in web.config your session cookies will no longer function without https.

<httpCookies requireSSL="true" />

However, this will give you a new problem if you run in a test environment or debug session without https. Since the cookie will no longer work, neither will your site. Here come transforms to the requeue. Since VS 2010 each web.config has two additional files for release and debug builds, enabling you to swap out sections or attributes. By adding the following section to your web.debug.config, your debug builds will automagicaly no longer require ssl for your cookies:

<system.web>
  <compilation xdt:Transform="RemoveAttributes(debug)" />
  <httpCookies xdt:Transform="Replace" requireSSL="false" />
</system.web>

If you also use secure forms authentication, you will need to make the same changes for the authentication part of the site:

<authentication mode="Forms">
   <forms . . .   requireSSL="true" />
</authentication>