CSRF Protection in AJAX Requests using MVC2

Posted by mnemosyn on Stack Overflow See other posts from Stack Overflow or by mnemosyn
Published on 2010-02-28T04:41:46Z Indexed on 2010/04/03 6:53 UTC
Read the original article Hit count: 405

Filed under:
|
|
|
|

The page I'm building depends heavily on AJAX. Basically, there is just one "page" and every data transfer is handled via AJAX. Since overoptimistic caching on the browser side leads to strange problems (data not reloaded), I have to perform all requests (also reads) using POST - that forces a reload.

Now I want to prevent the page against CSRF. With form submission, using Html.AntiForgeryToken() works neatly, but in AJAX-request, I guess I will have to append the token manually? Is there anything out-of-the box available?

My current attempt looks like this:

I'd love to reuse the existing magic. However, HtmlHelper.GetAntiForgeryTokenAndSetCookie is private and I don't want to hack around in MVC. The other option is to write an extension like

public static string PlainAntiForgeryToken(this HtmlHelper helper)
{
    // extract the actual field value from the hidden input
    return helper.AntiForgeryToken().DoSomeHackyStringActions();
}

which is somewhat hacky and leaves the bigger problem unsolved: How to verify that token? The default verification implementation is internal and hard-coded against using form fields. I tried to write a slightly modified ValidateAntiForgeryTokenAttribute, but it uses an AntiForgeryDataSerializer which is private and I really didn't want to copy that, too.

At this point it seems to be easier to come up with a homegrown solution, but that is really duplicate code.

Any suggestions how to do this the smart way? Am I missing something completely obvious?

© Stack Overflow or respective owner

Related posts about ASP.NET

Related posts about asp.net-mvc-2