How to secure Cookie when using Https

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.

var cookie = new HttpCookie("MyCookieName", "MyValue");
cookie.Secure = true;

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.

<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.

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.

@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.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.