Why does @Html.AntiForgeryToken() generate different tokens in same response?

user1023602 picture user1023602 · Mar 18, 2014 · Viewed 12.2k times · Source

A single Razor view contains several forms, each with its own call to @Html.AntiForgeryToken()

<form id="f1">
    @Html.AntiForgeryToken()
</form>

<form id="f2">
    @Html.AntiForgeryToken()
</form>

As I understand it, both of these anti forgery tokens should be the same.

<form id="f1">
    <input name="__RequestVerificationToken" type="hidden" value="duVT4VtiYybun-61lnSY1ol__qBwawnELooyqT5OSrCJrvcHvDs_Nr9GLxNxwvBaI4hUcKZVkm6mDEmH2UqNorHD1FnJbKJQLWe8Su_dhy_nnGGl5GhqqC3yRGzcxbBM0" />
</form>

<form id="f2">
    <input name="__RequestVerificationToken" type="hidden" value="ZMISz3IWHU_HCKP4FppDQ5lvzoYhlQGhN1cmzKBPz4OgDzyqSUK3Q1dqvw1uHsb4eNyd9U3AbFcnW8tR7g1QS8Dyhp0tFc-ee1sfDAOqbLCcgd3PDnLCbXx09pnPREaq0" />
</form>

Why are the values different?

Surely they should be the same, because they are sent in the same Response from the server?
The documentation says nothing about calling it once only.

Answer

vtortola picture vtortola · Mar 18, 2014

I am afraid that won't work.

The antiforgery token also travels in the response cookie, so yours will contain just the last token, and therefore the first form will always fail.

You can try to do something like this:

@{
    ViewBag.Title = "Index";
    var token = Html.AntiForgeryToken();
}

<form id="f1">
    @token 
</form>

<form id="f2">
    @token 
</form>

I have tried it, and the same token is used in both forms.