Symfony的CSRF和Ajax [英] Symfony CSRF and Ajax

查看:217
本文介绍了Symfony的CSRF和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.

什么是实现此一pretty的简单的方法?

What would be a pretty straightforward way to implement this?

在使用表单我只是做$形式 - > 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:

$csrf = $this->get('form.csrf_provider'); //Symfony\Component\Form\Extension\Csrf\CsrfProvider\SessionCsrfProvider by default
$token = $csrf->generateCsrfToken($intention); //Intention should be empty string, if you did not define it in parameters

return new Response($token);

这个问题可能对您有用

这篇关于Symfony的CSRF和Ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆