csrf_token symfony2验证

时间:2014-03-21 06:15:47

标签: forms validation symfony token csrf

我正在使用symfony2,当我尝试在自定义表单中验证csrf令牌时遇到问题,我的问题是如何验证控制器中的csrf令牌?

在我看来,这是我的代码。

<form role="form" action="{{ path('default_select_city_check') }}" method="post">
       <input type="hidden" name="_csrf_token" value="{{ csrf_token('default_select_city_check') }}">
            ...
        </form>

这是我在控制器中的代码:

public function selectCityCheckAction(Request $request) {
    // in this part, how can I compare the token value in the form with the token value in the session?
}

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

在控制器中添加一个功能:

 public function isCsrfTokenValid($intention, $token_name = '_csrf_token')
 {
    return $this->get('form.csrf_provider')
        ->isCsrfTokenValid($intention, $this->getRequest()->get($token_name));
 }

在你的行动中:

if ($this->isCsrfTokenValid('default_select_city_check')) {
   //do something you want
}