使用相同站点cookie属性防止CSRF

iml*_*lim 24 asp.net iis cookies csrf

我正在网上冲浪,发现文章使用相同网站的cookie属性预防CSRF.

在链接维护上我们需要添加Set-Cookie标头.

Set-Cookie:key = value; 仅Http; SameSite =严格

现在我的问题是,我想在我的ASP.NET站点中设置所有Cookie和身份验证Cookie.我尝试使用IIS中的标头来设置它,但有人说这是错误的实现方式.

我也在下面尝试过.

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

但它似乎没有帮助我.

请建议我更好的方法来做到这一点.

谢谢.

iml*_*lim 29

经过对HttpCookie Source的深入审核后,我们确认我们无法对代码执行此操作,因为无法在Cookie上添加额外属性,并且类被标记为已密封.

但无论如何我仍然通过修改web.config来管理解决方案,如下所示.

<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>
Run Code Online (Sandbox Code Playgroud)

这会在每个Set-Cookie上添加SameSite = strict.

  • 我尝试在.Net 4.7.2中使用&lt;httpCookies sameSite =“ Strict” /&gt;,但不适用于Asp.Net身份cookie。这个重写规则确实做到了。 (3认同)
  • @L01NL 我的目标是 4.7.2,但仍然得到 `Unrecognized attribute 'samesite'`,MS 文档中也没有提到 (3认同)
  • 从Asp.NET 4.7.2开始,你可以通过在Web.config中的`<system.web>`节点添加以下行来做同样的事情.`<httpcookies samesite ="严格"/>` (2认同)

And*_* RB 12

为了将 SameSite 定义为 ASP.NET_SessionId cookie,我必须在 system.web 部分下设置 web.config:

<sessionState cookieSameSite="Lax" />
Run Code Online (Sandbox Code Playgroud)

  • 多谢。这对我有用。只是想指出 &lt;httpCookies sameSite="None/Strict/Lax" /&gt; 对我不起作用。 (2认同)

tif*_*tif 10

.NET 4.7.2现在具有对SameSite属性的内置支持。
HttpCookie现在有一个叫做财产SameSite Microsoft 此处
查看更多信息。

不再需要通过配置文件来破解它。

  • 我不知道为什么,但我仍然看到警告“不允许使用‘sameSite’属性。” (2认同)

Kev*_*ith 8

您还可以在创建Cookie时在代码中进行设置:

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

Response.SetCookie(httpCookie);
Run Code Online (Sandbox Code Playgroud)

这将为您提供以下标题:

Set-Cookie:mycookie=myvalue; path=/;SameSite=Strict
Run Code Online (Sandbox Code Playgroud)

直到将其推送到框架中为止。


max*_*dbe 7

因为在这个时代,我们使用owin来修复相同的傻webapi cookie错误。

public class CookieSameSiteMiddleware : OwinMiddleware
{
    public CookieSameSiteMiddleware(OwinMiddleware next) : base(next)
    {
    }

    public override async Task Invoke(IOwinContext context)
    {
        var url = context.Request.Path.Value.ToLowerInvariant();

        if (url.Contains("/api/mylogin"))
        {
            context.Response.OnSendingHeaders(x =>
            {
                var scv = context.Response.Headers.FirstOrDefault(h => h.Key == "Set-Cookie");
                if (!scv.Equals(default(KeyValuePair<string, string[]>)))
                {
                    //context.Response.Headers.Remove("Set-Cookie");
                    context.Response.Headers.Set("Set-Cookie", scv.Value[0] + "; SameSite=strict");
                }

            }, null);
        }

        await this.Next.Invoke(context);
    }
}
Run Code Online (Sandbox Code Playgroud)

确保在.UseWebApi()之前注册了中间件

  • +1 这种方法效果很好。代码中有一个小错误——当您的登录页面设置多个 cookie 时,它​​会过滤掉 cookie。我修复了错误并完善了代码 [here](https://gist.github.com/mkropat/e98bf09be76f7bea9cca91aa21b725de)。 (2认同)

Ale*_*lex 6

只需添加我的答案即可系统化此处和其他位置找到的所有信息。

1.要保护4.7.2及更高版本下的自定义Cookie

var c = new HttpCookie("test");
c.SameSite = SameSiteMode.Lax;
Run Code Online (Sandbox Code Playgroud)

2.保护表单身份验证cookie

在web.config中

<authentication mode="Forms">
    <forms ..... cookieSameSite="Lax" />
</authentication>
Run Code Online (Sandbox Code Playgroud)

3.保护ASP.NET会话cookie

在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;
}
Run Code Online (Sandbox Code Playgroud)

有趣的事实:即使设置<httpCookies requireSSL="true" />了ASP.NET会话cookie,由于某种原因,它仍然是不安全的。

4. <httpCookies samesite=xxx>不存在

<httpCookies sameSite="Strict" />像在web.config中的上面的注释中建议的那样添加无效,我收到了错误。

无法识别的属性“ samesite”

即使我的目标是4.7.2。在多个项目和多台机器上进行了测试,VS2019也不在intellisense中显示此信息,MS文档也没有在任何地方提及它。

  • 我正在使用 4.7.2,并在错误列表“不允许使用‘sameSite’属性。”下收到警告。它允许我构建解决方案,但不确定此警告。 (3认同)
  • 如何在.NET 4.6.2中实现该解决方案? (2认同)