Session cookies are often seen as one of the biggest problems for security and privacy with HTTP, yet often times, it’s necessary to utilize it to maintain state in modern web applications. By default, it is insecure and vulnerable to be intercepted by an authorized party.
Cookies typically store session identifiers that may offer full access to an account, therefore if a cookie is intercepted, a session can be hijacked by someone who is not the real user but pretending as that user.
For this reason, it’s very important that we need to set parameters on how the cookies are passed and have it encrypted as they get sent/read between a web server and the browser.
In order to make cookies more secure to use, there are two things we need to pay attention to, they are HttpOnly and Secure flags.
HttpOnly Flag
The first flag we need to set up is HttpOnly flag. By default, when there’s no restriction in place, cookies can be transferred not only by HTTP, but any JavaScript files loaded on a page can also access the cookies. This ability can be dangerous because it makes the page vulnerable to cross-site scripting (XSS) attack.
The only way to restrict this is by setting HttpOnly flag, which means the only way cookies are sent is via HTTP connection, not directly through other means (i.e., JavaScript).
Secure Flag
The second flag we need to pay attention to is Secure flag. This flag highlights the second issue that by default cookies are always sent on both HTTP and HTTPS requests. A malicious attacker who can’t see encrypted traffic with HTTPS connection can easily switch to HTTP connection and access the same cookie because it is not encrypted. Therefore, we need to set the Secure flag to ensure that the cookie in encrypted when it’s created.
Enable HttpOnly Flag in IIS
Edit the web.config file of your web application and add the following:
<system.web>
...
<httpCookies httpOnlyCookies="true" requireSSL="true" />
...
</system.web>
Enable Secure Flag in IIS
To enable secure flag in IIS, it is better to use URL Rewrite and add the following to your web.config file:
<system.webServer>
<rewrite>
<outboundRules>
<rule name="Use only secure cookies" preCondition="Unsecured cookie">
<match serverVariable="RESPONSE_SET_COOKIE" pattern=".*" negate="false" />
<action type="Rewrite" value="{R:0}; secure" />
</rule>
<preConditions>
<preCondition name="Unsecured cookie">
<add input="{RESPONSE_SET_COOKIE}" pattern="." />
<add input="{RESPONSE_SET_COOKIE}" pattern="; secure" negate="true" />
</preCondition>
</preConditions>
</outboundRules>
</rewrite>
...
</system.webServer>