How to secure Cookie when using Https<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

How to secure Cookie when using Https

Posted on: December 1, 2011

By default cookie are not secured when using Https with SSL(TSL) security. security with cookies

You have two choices with ASP.NET

The first one is to explicitly mark the cookie has secure.

1var cookie = new HttpCookie("MyCookieName", "MyValue");
2cookie.Secure = true; Response.Cookies.Add(cookie);

The advantage is that not even if the page is accessed with http that the cookie will still works. But, it has the cost to add more code.

The second choice is to change in the web.config a line that will implicit all cookie to be secure. But, the disadvantage is that the http won't work, only https.

1<httpCookies requireSSL="true" />

Asp.Mvc security with cookies

On the other side, with ASP MVC if you want to secure you have two ways and it's better to use both of them in the same time.

The first approach is to use Https attribute to the controller class.

1[RequireHttps] public class MyLoginController: Controller { ...

This will create a 302 redirect to the Https version of this page. If you want to avoid having a call two times to the server (avoid the redirect) you can also use the overloaded method of ActionLink which let you specify the protocol.

1@Html.ActionLink("My Login Link", "LogOn", "MyLoginController", "https", null, null, null, null)

So that's it. If you need to have a secured website, do not forget to secure your cookie.