Secure Cookie Attribute
Overview
The secure attribute is an option that can be set by the application server when sending a new cookie to the user within an HTTP Response. The purpose of the secure attribute is to prevent cookies from being observed by unauthorized parties due to the transmission of the cookie in clear text. To accomplish this goal, browsers which support the secure attribute will only send cookies with the secure attribute when the request is going to an HTTPS page. Said in another way, the browser will not send a cookie with the secure attribute set over an unencrypted HTTP request. By setting the secure attribute, the browser will prevent the transmission of a cookie over an unencrypted channel.
Setting the Secure Attribute
Following sections describes setting the Secure Attribute in respective technologies.
ASP.NET
Set the following in Web.config: <httpCookies requireSSL="true" />
For some objects that have a requireSSL property, like the forms Authentication Cookie, set the requireSSL="true"
attribute in the web.config for that specific element. For example:
<code><authentication mode="Forms"></code>
<code><forms loginUrl="member_login.aspx"</code>
<code>cookieless="UseCookies"</code>
<code>‘‘‘requireSSL="true"‘‘‘</code>
<code>path="/MyApplication" /></code>
<code></authentication></code>
Which will enable the secure attribute on the Forms Authentication cookie, as well as checking that the http request is coming to the server over SSL/TLS connection. Note that in case TLS is offloaded to a load balancer, the requireSSL solution wouldn’t work.
Alternatively, the cookies can be set to secure programmatically using the following code by adding a EndRequest event handler to the Global.asax.cs
file:
protected void Application_EndRequest(Object sender, EventArgs e) {
// Iterate through any cookies found in the Response object.
foreach (string cookieName in Response.Cookies.AllKeys) {
Response.Cookies[cookieName]?.Secure = true;
}
}