I have an MVC view that is supposed to be iFramed. And several instances of it might be iFramed in the same host page. In my view I have this:
@Html.AntiForgeryToken()
Which I use to try to make sure calls to a web api are only coming from this page. My host page might look something like this:
<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>
In my view I grab the token and submit it in a header so that I can check it in my 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);
The problem I'm running into is that in my host page, all three views are getting loaded in parallel. As a result they all get their own random token in a hidden field and try to set the cookie. But while there can be three separate independent hidden input tokens, there can be only one cookie. So of the three requests, two will fail and one will succeed. A reload of the page will have all three working again, presumably because they are all getting the same anti-forgery token at this point (because it belongs to the session - if I understand this correctly).
So how can I avoid this? How can I make sure they all get the same token?