防止CSRF具有相同站点的Cookie属性 [英] Preventing CSRF with the same-site cookie attribute
问题描述
我正在网上冲浪,发现文章使用相同站点的cookie属性防止CSRF .
I was surfing the web and found article Preventing CSRF with the same-site cookie attribute.
关于链接维护,我们需要添加Set-Cookie标头.
As on link maintain We need to add Set-Cookie header.
Set-Cookie:键=值; HttpOnly; SameSite = strict
Set-Cookie: key=value; HttpOnly; SameSite=strict
现在我的问题是,我想在我的ASP.NET站点的所有Cookie和身份验证Cookie中进行设置. 我尝试使用IIS中的标头设置此设置,但有人说这是错误的实现方式.
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.
我也在下面尝试过.
HttpCookie newAuthenticationCookie = new HttpCookie(FormsAuthentication.FormsCookieName
, FormsAuthentication.Encrypt(newAuthenticationTicket))
{
HttpOnly = true
};
newAuthenticationCookie.Values.Add("SameSite", "strict");
但是似乎没有帮助我.
请向我建议一种更好的方法.
Please suggest me a better way to do this.
谢谢.
推荐答案
在 HttpCookie源,确认无法使用代码执行此操作,因为无法在Cookie上添加额外的属性,并且将类标记为已密封.
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.
但是无论如何,我仍然可以通过如下修改 web.config 来管理解决方案.
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>
这会在每个 Set-Cookie 上添加 SameSite = strict .
这篇关于防止CSRF具有相同站点的Cookie属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!