Question

I have an HTML form, to which I dynamically add a text field and perform a POST request for that form via jQuery to an ASP.NET MVC controller.

If I invoke the POST request without the ValidateAntiForgeryToken attribute on the controller action, it works fine. But, when I add the ValidateAntiForgeryToken attribute to the action I get the following exception:

"A required anti-forgery token was not supplied or was invalid."

Does anyone any ideas as to why this might be?

One point of note is that the token id in the cookie appears to be completely different to the token rendered in the form. Why might these be different?

The action:

[AcceptVerbs(HttpVerbs.Post)]
[ValidateAntiForgeryToken]
public string MyAction(Guid id, Dto dto)
{            
  //return JSON;
}  

The form (as rendered):

<form id="slider" class="fc" method="post" action="/controller/myaction/" name="tabEdit">
  <span id="slider_previous" class="sprite" tabindex="0" title="foo">Previous</span>
  <input type="hidden" value="mzyg7UWQrHwafoSuoJBvwfraQEtCTAmM9QHYeyMSrAHFHG10BNXM+I2yNgz8zQ8yu/E43eF3yMuHX7YIQwmK3Q==" name="__RequestVerificationToken"/>
  <div id="sliderWrap" style="width: 31.243%;">
    <ul class="sliderList">
      <li id="ID_3d031daf-a7f9-46f2-b4b9-7c9fc6560e3d">
      </li>
      <li id="ID_78b61634-d88a-4f33-8e48-e0655ad8a958" class="current">
        <input class="sliderInput" type="text" value="" name="Bar"/>
        <a class="sprite" href="/a/b/78b61634-d88a-4f33-8e48-e0655ad8a958">Delete</a>
      </li>
    </ul>
  </div>
<span id="slider_addNew" class="sprite" tabindex="0" title="Add new">New</span>
<span id="slider_next" class="sprite" tabindex="0" title="See next">Next</span>
</form>

The original view rendering the anti-forgery token:

<form id="slider" class="fc" method="post" action="/controller/myaction/" name="tabEdit">
<%=Html.AntiForgeryToken(OurNamespace.MVC.Constants.SaltValue) %>
  <ul class="noJs">
<!-- etc -->       
  </ul>
</form>
Was it helpful?

Solution

You are specifying a custom salt when you generate your AntiForgeryToken, you need to provide this salt to the ValidateAntiForgeryToken attribute as well.

[ValidateAntiForgeryToken(Salt=OurNamespace.MVC.Constants.SaltValue)]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top