Php Symfony2,登录表单-CSRF保护

Php Symfony2,登录表单-CSRF保护,php,forms,symfony,csrf,Php,Forms,Symfony,Csrf,我有此登录表单,包含以下细枝模板内容: <form action="{{ path('login_check') }}" method="post"> <div class="input form"> <label for="username">Account name or E-mail:</label> <input type="text" id="username" name="_username" va

我有此登录表单,包含以下细枝模板内容:

<form action="{{ path('login_check') }}" method="post">
    <div class="input form">
      <label for="username">Account name or E-mail:</label>
      <input type="text" id="username" name="_username" value="{{ last_username }}" required="required" />
    </div>
    <div class="input form">
      <label for="password">Password:</label>
      <input type="password" id="password" name="_password" required="required" />
    </div>
    <input type="hidden" name="_token" value="{{ csrf_token("intention") }}">
    <button type="submit">Log In</button>
</form>

帐户名或电子邮件:
密码:
登录
我想在这个表单中添加CSRF保护。如您所见,我添加了这一行
,但我不确定它是否足以激活此保护

我的控制器的表单与文档上的表单相同,因此如下所示:

<?php
// src/Acme/SecurityBundle/Controller/SecurityController.php;
namespace Acme\SecurityBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;

class SecurityController extends Controller
{
    public function loginAction()
    {
        $request = $this->getRequest();
        $session = $request->getSession();

        // get the login error if there is one
        if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
            $error = $request->attributes->get(
                SecurityContext::AUTHENTICATION_ERROR
            );
        } else {
            $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
            $session->remove(SecurityContext::AUTHENTICATION_ERROR);
        }

        return $this->render(
            'AcmeSecurityBundle:Security:login.html.twig',
            array(
                // last username entered by the user
                'last_username' => $session->get(SecurityContext::LAST_USERNAME),
                'error'         => $error,
            )
        );
    }
}

默认情况下启用CSRF保护,因此您只需在HTML中呈现CSRF令牌。您不需要在控制器中执行任何操作

您有两个选择:

  • 像上面那样做
  • 使用时,这将渲染所有尚未渲染的字段,包括隐藏字段(如CSRF标记)

  • 两者都可以。我发现@Chris McKinnel的答案是不正确的。现在,Symfony2在教程页面上有以下部分:

    我需要在我的security.yml中添加行:

    改变这个

    <input type="hidden" name="_token" value="{{ csrf_token("intention") }}">
    
    
    

    
    

    现在我确信我的身份验证表单受CSRF保护。

    但是此登录没有生成表单,因此我无法使用此功能。是否需要调用任何表单“form_login”?@Sekai这是标识登录表单的配置项。在这个项目中,您可以设置登录操作的路径,或者,正如您在这个答案中看到的,也可以为csrf提供者设置选项。是的,我同意,但我尝试在表单中操作令牌(我添加了随机字符)并提交了我的表单,并且成功了。保护是如何工作的?通过FireBug,我更改生成的令牌的值,以测试我的表单是否成功。不幸的是,即使我手动更改了crsf令牌,登录也成功了。这意味着没有设置保护,我想?但是的,在你的第一条评论中,你提到了设置登录操作的路由,我在哪里设置它?有必要吗?
    <input type="hidden" name="_token" value="{{ csrf_token("intention") }}">
    
    <input type="hidden" name="_csrf_token" value="{{ csrf_token("authenticate") }}">