Symfony CSRF 和 Ajax [英] Symfony CSRF and Ajax
问题描述
我正在尝试在我的 Symfony 2 项目中实现一些 ajax 功能.使用 jquery 的 $.post 我想将一些数据发送回我的控制器.然而,当我只是发布数据时,没有 CSRF 保护到位,因为 symfony 的 csrf 保护似乎只适用于表单.
I am trying to implement some ajax functionality in my Symfony 2 project. Using jquery's $.post I want to send some data back to my controller. However, when I just POST the data no CSRF protection is in place, as symfony's csrf protection only seems to apply to forms.
实现这一点的非常简单的方法是什么?
What would be a pretty straightforward way to implement this?
使用表单时,我只需执行 $form->isValid() 即可确定 CSRF 令牌是否通过.我目前正在将我想发布的所有内容放在表单中,然后发布.这基本上意味着我只使用该表单来实现 CSRF 保护,这似乎很糟糕.
When using forms I can just do $form->isValid() to find out whether or not the CSRF token passes. I am currently placing everything I want to POST in a form and then posting that. Which basically means I am only using that form to implement CSRF protection, which seems hacky.
推荐答案
在 Symfony2 中 CSRF 令牌默认是基于会话的.如果你想生成它,你只需要得到这个服务和调用生成方法:
In Symfony2 CSRF token is based on session by default. If you want to generate it, you just have to get this service and call generation method:
//SymfonyComponentFormExtensionCsrfCsrfProviderSessionCsrfProvider by default
$csrf = $this->get('form.csrf_provider');
//Intention should be empty string, if you did not define it in parameters
$token = $csrf->generateCsrfToken($intention);
return new Response($token);
这个问题可能对你有用
这篇关于Symfony CSRF 和 Ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!