Preventing CSRF with the same-site cookie attribute

After Deep review on HttpCookie Source it's confirm that we cannot do this with the code, as there is no way to add extra attribute on Cookie and class is marked as sealed.

But still anyhow I manage solution by modifying web.config as below.

<rewrite>
  <outboundRules>
    <rule name="Add SameSite" preCondition="No SameSite">
      <match serverVariable="RESPONSE_Set_Cookie" pattern=".*" negate="false" />
      <action type="Rewrite" value="{R:0}; SameSite=strict" />
      <conditions>
      </conditions>
    </rule>
    <preConditions>
      <preCondition name="No SameSite">
        <add input="{RESPONSE_Set_Cookie}" pattern="." />
        <add input="{RESPONSE_Set_Cookie}" pattern="; SameSite=strict" negate="true" />
      </preCondition>
    </preConditions>
  </outboundRules>
</rewrite>

This add SameSite=strict on each Set-Cookie.


Just adding my answer to systematize all the info found here and in other places.

1. To secure custom cookies under 4.7.2 and later

var c = new HttpCookie("test");
c.SameSite = SameSiteMode.Lax;

2. To secure Forms authentication cookie

In web.config

<authentication mode="Forms">
    <forms ..... cookieSameSite="Lax" />
</authentication>

3. To secure ASP.NET Session cookie

In Global.asax

void Session_Start(Object sender, EventArgs e)
{
    Response.Cookies["ASP.NET_SessionId"].SameSite = SameSiteMode.Lax;
    //while we're at it lets also make it secure
    if (Request.IsSecureConnection)
        Response.Cookies["ASP.NET_SessionId"].Secure = true;
}

Fun fact: even if you set <httpCookies requireSSL="true" /> the ASP.NET session cookie will still be non-secure for some reason.

3(a). UPDATE 01.2020: .NET 4.8 Session cookie is now "SameSite" by default

Installing the latest Windows Update will make your session cookies Lax by default. You can control it here:

<sessionState cookieSameSite="Lax" /> <!-- in system.web -->

4. <httpCookies samesite=xxx> does not exist?

Adding <httpCookies sameSite="Strict" /> like suggested in the comment above in web.config didn't work, I was getting the error.

Unrecognized attribute 'samesite'

Even though I'm targeting 4.7.2. Tested on multiple project and multiple machines, also VS2019 does not show this in intellisense and MS docs do not mention it anywhere.


You can also set this in code when creating a cookie:

var httpCookie = new HttpCookie("mycookie", "myvalue");
httpCookie.Path += ";SameSite=Strict";

Response.SetCookie(httpCookie);

This will give you the following header:

Set-Cookie:mycookie=myvalue; path=/;SameSite=Strict

bit of a hack until it's pushed in to the framework.


.NET 4.7.2 has now built-in support for SameSite property.
The HttpCookie has now a property called SameSite.
See more info here from Microsoft.

No need anymore to hack this through the config file.