I am having problems getting Microsoft's MVC's [ValidateAntiForgeryToken]
to work with a Single Page Application (SPA) written using Marionette & Backbone. The problem seems to be that the MVC [ValidateAntiForgeryToken]
method fails to see the token we send as part of the JSON. We thought it was because the token had to be in the Forms part of the reply but MrOggy85 says that isn't a problem (see his answer below).
The code is in my api controllers, which use AttributeRouting, which we assume is causing the problem. A typical action looks like this:
// POST api/vizschemes/
[POST("")]
[Authorize(Roles = "...some role...")]
[ValidateAntiForgeryToken]
public ActionResult Add(CreateUpdateSmVizSchemeDto dto, ICreateSmVizScheme service)
{
... code to update the VizScheme and return json
}
Has anyone else overcome this? A lot of googling turned up the comment in is post "ASP.NET MVC provides built-in support for anti-forgery tokens, through the AntiForgery class and the [ValidateAntiForgeryToken] attribute. Currently, this functionality is not built into Web API. However, the (KnockoutJS) template includes a custom implementation for Web API.". This suggests that they write their own, which I can do.
Has anyone else hit this, and if so how did you solve it? Am I missing something obvious or should I just write my own ValidateAntiForgeryToken method? Your input would be appreciated.
UPDATE
GREAT stackoverflow link provided by @MrOggy85 with lots more information in it. See How can i supply an AntiForgeryToken when posting JSON data using $.ajax? . I plan to write my own AntiForgery test and will post when I have done.