c# - 防伪 token 竞争条件

标签 c# asp.net-mvc iframe cookies

我有一个应该是 iFramed 的 MVC View 。它的多个实例可能在同一个主机页面中被 iFramed。在我看来,我有这个:

@Html.AntiForgeryToken()

我用它来尝试确保对 Web API 的调用仅来自此页面。我的主机页面可能看起来像这样:

<iframe src="http://myserver.com/myview?someparameters=0000"></iframe>
<iframe src="http://myserver.com/myview?someparameters=0001"></iframe>
<iframe src="http://myserver.com/myview?someparameters=0002"></iframe>

在我看来,我获取 token 并在 header 中提交它,以便我可以在我的 API 中检查它:

var headers = actionContext.Request.Headers;
var headerToken = headers.Contains("__RequestVerificationToken") ? headers.GetValues("__RequestVerificationToken").FirstOrDefault() : null;
var cookie = headers.GetCookies("__RequestVerificationToken").FirstOrDefault()?["__RequestVerificationToken"]?.Value;

AntiForgery.Validate(cookie,headerToken);

我遇到的问题是,在我的主机页面中,所有三个 View 都是并行加载的。结果,他们都在隐藏字段中获得了自己的随机标记,并尝试设置 cookie。但是,虽然可以有三个独立的隐藏输入 token ,但只能有一个 cookie。因此,在三个请求中,两个会失败,一个会成功。重新加载页面将使所有三个再次工作,大概是因为此时它们都获得了相同的防伪 token (因为它属于 session - 如果我理解正确的话)。

那么我该如何避免呢?我如何确保它们都获得相同的 token ?

最佳答案

尝试使用部分 View 。在每个局部 View 中,您可以使用 iFrame,所有局部 View 都将添加到具有 Html.AntiForgeryToken() 的主 .cshtml 文件

@Html.AntiForgeryToken()

<div>    
    @{Html.RenderPartial("_iFrame1");}
</ div>
<div>    
    @{Html.RenderPartial("_iFrame2");}
</ div>
<div>    
<div>
@{Html.RenderPartial("_iFrame3");}
</ div>

关于c# - 防伪 token 竞争条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44811958/

相关文章:

c# - 为什么 HTMLDocumentEvent onclick 会多次触发?

javascript - 如何通过表单提交插入后显示成功消息

javascript - 可拖动/可滚动区域内的 iFrame

html - 在没有iframe的情况下在Wordpress中包含jsp页面

google-maps - 嵌入式谷歌地图缩小/不居中并且通常有错误

C# 大对象和堆

c# - RX Subject<T> 如何取消订阅

c# - 为什么 wpf 复选框绑定(bind)可能无法工作?

asp.net-mvc - MVC2中区域的使用

c# - 414(请求 URI 太长)