Dragomok Dragomok - 1 year ago 349
ASP.NET (C#) Question

Setting session cookie to HttpOnly

I am developing an ASP.NET MVC server with Entity Framework 6.0. As far as I'm aware, it's set up to be compatible with EF 4.5 (

<httpRuntime targetFramework="4.5" />

I want to ensure that the session cookie (ie. cookie that stores the session identifier) is HttpOnly, since that's an industry-wide best practice, which helps protect against Cross-Site Request Forgery attacks.

The problem is, it's created automatically by the framework, so I can't simply change an object's property right after calling the constructor, as is the case with all the other cookies.

, I've set
<httpCookies httpOnlyCookies="true" />
, and yet - when I retrieve the session cookie - it is not HttpOnly (its HttpCookie.HttpOnly property is set
). And I don't quite know how to change that.

I couldn't find anything in Microsoft's documentation about
that would change that. Here on Stack Overflow I only found a four year old question talking about how session cookie is HttpOnly by default, which is the precise opposite for me, and a five days old question asking why session cookie is not HttpOnly by default - which for some inexplicable reason was closed - without a comment - as a duplicate of the former.

I know I can retrieve the session cookie, check it and set
on every request
(or do that less often with a slightly more refined/hackish filter, or set it manually on login, or...), but I'm not a blood-soaked barbarian there has to be a proper way to do this.

So, how do I set the session cookie to HttpOnly?

Win Win
Answer Source

Session Cookie will always be httponly. You cannot modify or override it.

when I retrieve the session cookie - it is not HttpOnly (its HttpCookie.HttpOnly property is set false).

var cookie = Request.Cookies["ASP.Net_SessionId"];
if (cookie != null)
    var httpOnly = cookie.HttpOnly; // <-- This is always false

HttpOnly value is always false at server-side, because client browser does not send back to server whether cookie is in httponly or not.

How can I verify

You can use cookie editor such as Chrome Plugin EditThisCookie.

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download