php - Symfony2,登录表单 - CSRF 保护

标签 php forms symfony csrf

我通过 Symfony2 security documentation 有此登录表单具有以下 TWIG 模板内容:

<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 保护。正如你所看到的,我添加了这一行 <input type="hidden" name="_token" value="{{ csrf_token("intention") }}">但我不太确定是否足以激活此保护。

我的 Controller 与文档上的形式相同,所以它看起来像这样:

<?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_token("intention") }} 的隐藏输入就足够了或者我必须在 Controller 中添加一些东西?

最佳答案

我发现 @Chris McKinnel 的回答不正确。现在,Symfony2 在教程页面上有此部分:

http://symfony.com/doc/current/cookbook/security/csrf_in_login_form.html

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

    form_login:
        # ...
        csrf_provider: form.csrf_provider

并改变这个

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

<input type="hidden" name="_csrf_token" value="{{ csrf_token("authenticate") }}">

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

关于php - Symfony2,登录表单 - CSRF 保护,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19360146/

相关文章:

php - Laravel CSS 文件链接修正

php - 为什么使用 PHP 上传文件时 Linux 会创建没有扩展名的临时文件,而 Windows 会创建带有扩展名的临时文件?

php - 未处理为订单表 html 输入表单创建插入语句

forms - 具有单个文本输入字段的 Bootstrap 模式对话框始终在 Enter 键上关闭

php - symfony 5.3 上传文件的问题

php - 如何用GET参数转发?

php - 数据表: update table in realtime with animation

ajax - jQuery Form 插件不会调用 IE 8 中的方法

mysql - 在 Doctrine 模式中,当我添加新字段时无法更新

php - 使用 For Each 使用 JSON 对象更新 MySQL -- 复选框