asp.net - why - set samesite attribute of cookies to lax/strict




Preventing CSRF with the same-site cookie attribute (4)

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

No need anymore to hack this through the config file.

I was surfing 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 seem like not helping me.

Please suggest me a better way to do this.

Thanks.


After Deep review on HttpCookie Source it's confirm that we can not 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.


Pre 4.7.2 you can just append the string to the cookie path.

FormsAuthentication.SetAuthCookie(username, false, FormsAuthentication.FormsCookiePath + "; SameSite=Lax");

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.







csrf