8

I have a problem with forms submitted with ajax. I do my forms with Zend Framework. Some are real forms so I add a Hash element. Others are for small operations (like upvote and downvote here) so I do them with links.

My problem is that I need to use ajax especially for the small forms (the links). I see a lot of questions but nothing comprehensive enough to solve the problem. Is there a detailed description on how to get csrf token working smoothly when forms are submitted via ajax? preferably with Zend Framework but general PHP answers will help too.

samquo
  • 757
  • 7
  • 21

2 Answers2

7

You don't need a CSRF token. You case use the HTTP_X_REQUESTED_WITH method (see e.g. here).

Alfred
  • 21,058
  • 61
  • 167
  • 249
Artefacto
  • 96,375
  • 17
  • 202
  • 225
  • I read about the REQUESTED_WITH header in this question http://stackoverflow.com/questions/3664044/anti-csrf-token-and-javascript/3665136#3665136 but the comments by Rook (and the answer itself) say it's not really safe. So if I use it, I think I still need to add "something else" to it. What's your opinion? – samquo Jan 22 '11 at 20:34
  • @samquo haha I like how my name comes up a lot on SO security. But its true, if you check x_requested_with its unexploitable due to the same origin policy for XHR. – rook Jan 22 '11 at 20:59
  • 2
    BTW, you may want to look into different behavior than just trusting REQUESTED_WITH: both Rails and Django have been updated recently to account for instances where that may not be sufficient protection. Here's Django's notes on their update: http://is.gd/JLBrfL I'm not sure how to accomplish that with Zend, though :) I happened to find this while searching for CSRF and AJAX. – Rob Mar 08 '11 at 15:11
  • @Rob Thanks for the pointer. I wonder what the exploit is, though. All it says is "combinations of browser plugins and HTTP redirects". Sounds like a browser plugin bug. – Artefacto Mar 08 '11 at 19:01
  • 1
    @Artefacto you can read details about the exploit at http://lists.webappsec.org/pipermail/websecurity_lists.webappsec.org/2011-February/007533.html – Simon Lieschke Oct 11 '11 at 20:22
0

For those coming to this page, it is possible to get csrf working with ajax.

In the controller you will need to regenerate the hash using via adding this right before the end of the action:

$form->hash->initCsrfToken();

$this->view->csrfhash = $form->hash->getValue();

In the js file you're using to do the ajax, you're going to need to use a selector to find the instance of the hash as it is created (so for jquery:

$(#hash).replaceWith(csrfhash); Actually if you use replaceWith you're going to replace the entire hidden csrf element including the id and name. But that part should be fairly easy to do.

Community
  • 1
  • 1
twunde
  • 84
  • 2