简体   繁体   English

ajax的CSRF令牌

[英]CSRF token for ajax

I have a problem with forms submitted with ajax. 使用ajax提交的表单有问题。 I do my forms with Zend Framework. 我用Zend Framework做我的表单。 Some are real forms so I add a Hash element. 有些是真实的形式,所以我添加了一个Hash元素。 Others are for small operations (like upvote and downvote here) so I do them with links. 其他用于小型操作(如upvote和downvote),所以我用链接做。

My problem is that I need to use ajax especially for the small forms (the links). 我的问题是我需要使用ajax,尤其是小型表单(链接)。 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? 有关如何通过ajax提交表单时如何使csrf令牌顺利运行的详细说明? preferably with Zend Framework but general PHP answers will help too. 最好使用Zend Framework,但一般的PHP答案也会有所帮助。

You don't need a CSRF token. 您不需要CSRF令牌。 You case use the HTTP_X_REQUESTED_WITH method (see eg here ). 您的情况使用HTTP_X_REQUESTED_WITH方法(参见此处 )。

For those coming to this page, it is possible to get csrf working with ajax. 对于那些访问此页面的人来说,可以让csrf使用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(); $形式 - >散列> initCsrfToken();

$this->view->csrfhash = $form->hash->getValue(); $ 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: 在用于执行ajax的js文件中,您将需要使用选择器来查找创建时的哈希实例(因此对于jquery:

$(#hash).replaceWith(csrfhash); $(#哈希).replaceWith(csrfhash); Actually if you use replaceWith you're going to replace the entire hidden csrf element including the id and name. 实际上,如果你使用replaceWith,你将替换整个隐藏的csrf元素,包括id和name。 But that part should be fairly easy to do. 但那部分应该相当容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM