Preventing CSRF with the same-site cookie attribute

imlim picture imlim · Aug 15, 2016 · Viewed 52.1k times · Source

I was surfing the web and found article Preventing CSRF with the same-site cookie attribute.

As on link maintain We need to add Set-Cookie header.

Set-Cookie: key=value; HttpOnly; SameSite=strict

Now My Question is, I want to set this in my ASP.NET site in all Cookies and Authentication Cookie. I tried to set this using header from IIS but someone says this is wrong way implementation.

I have also tried below.

HttpCookie newAuthenticationCookie = new HttpCookie(FormsAuthentication.FormsCookieName
                    , FormsAuthentication.Encrypt(newAuthenticationTicket))
                {
                    HttpOnly = true
                };
newAuthenticationCookie.Values.Add("SameSite", "strict");

But it seems like not helping me.

Please suggest me a better way to do this.

Thanks.

Answer

imlim picture imlim · Aug 15, 2016

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.