POST数据中存在_token,但表单失败并显示错误:“CSRF令牌无效。请尝试重新提交表单”

时间:2017-03-06 20:11:37

标签: php symfony symfony-forms

我知道这个主题已经在SO中讨论了好几次但是我已经检查了很多主题,似乎没有像我的那样,到目前为止,我测试的并不是解决我的问题。我首先使用Symfony 3.2.4和PHP 7.1.2。

我的控制器中有以下代码:

class QuoteController extends Controller
{
    /**
     * @Route("/quote/register")
     */
    public function registerAction()
    {
        $entity = new Quote();
        $form   = $this->createForm(QuoteType::class, $entity);

        return $this->render(
            'QuoteBundle:Quote:register.html.twig',
            ['entity' => $entity, 'form' => $form->createView()]
        );
    }

    /**
     * @Route("/quote/save", name="save-quote")
     */
    public function saveAction()
    {
        $entity = new Quote();
        $form   = $this->createForm(QuoteType::class, $entity);

        $request = Request::createFromGlobals();
        $form->handleRequest($request);

        if ($form->isValid()) {
            dump($form->getData());
        } else {
            dump($_POST);
            dump($form->getErrors());
        }

        die();
    }
}

这就是QuoteType的样子:

class QuoteType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array                $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('schneider_quote_id')
            ->add('agreement_number')
            ->add('quote_creation_source')
            ->add('quote_status')
            ->add('distributor_id')
            ->add('start_date', DateType::class)
            ->add('end_date', DateType::class)
            ->add('save', SubmitType::class, ['label' => 'Create Post']);
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Quote::class,
        ]);
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'quote';
    }
}

最后这就是我的模板寄存器的样子:

{% block body %}
    {{ form_start(form, {'action': path('save-quote'), 'method': 'POST'}) }}
    {{ form_errors(form) }}
    {{ form_widget(form) }}
    {{ form_row(form._token) }}
    {{ form_end(form) }}
{% endblock %}

但是当我发送表格时,我收到了错误:

  

CSRF令牌无效。请尝试重新提交表单。

如果您发现表单错误中有dump() $_POST个数据,那就是结果:

dump($_POST);
array:1 [▼
  "quote" => array:9 [▼
    "schneider_quote_id" => "100"
    "agreement_number" => "100"
    "quote_creation_source" => "sdasdasd"
    "quote_status" => "sadsad"
    "distributor_id" => "2"
    "start_date" => array:3 [▶]
    "end_date" => array:3 [▶]
    "save" => ""
    "_token" => "bSuU7h7rDR-_FkEGZ3zS60OtIofs_1bAi-J-YdCtxlM"
  ]
]

dump($form->getErrors());
FormErrorIterator {#32 ▼
  -form: Form {#672 ▼
    -config: FormBuilder {#673 ▶}
    -parent: null
    -children: OrderedHashMap {#674 ▶}
    -errors: array:1 [▼
      0 => FormError {#625 ▶}
    ]
    -submitted: true
    -clickedButton: SubmitButton {#787 ▶}
    -modelData: Quote {#444 ▶}
    -normData: Quote {#444 ▶}
    -viewData: Quote {#444 ▶}
    -extraData: []
    -transformationFailure: null
    -defaultDataSet: true
    -lockSetData: false
  }
  -errors: array:1 [▼
    0 => FormError {#625 ▼
      -message: "The CSRF token is invalid. Please try to resubmit the form."
      #messageTemplate: "The CSRF token is invalid. Please try to resubmit the form."
      #messageParameters: []
      #messagePluralization: null
      -cause: null
      -origin: Form {#672}
    }
  ]
}

问题是为什么如果Symfony没有正确读取POST数据中的_token

我已经从CSRF Protection阅读了The Form Components的文档,我现在很困惑,也许Symfony 3中的内容发生了变化,我不知道。我是否需要以某种方式在控制器中使用这段代码?

use Symfony\Component\Form\Forms;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Form\Extension\Csrf\CsrfExtension;
use Symfony\Component\Security\Csrf\TokenStorage\SessionTokenStorage;
use Symfony\Component\Security\Csrf\TokenGenerator\UriSafeTokenGenerator;
use Symfony\Component\Security\Csrf\CsrfTokenManager;

// create a Session object from the HttpFoundation component
$session = new Session();

$csrfGenerator = new UriSafeTokenGenerator();
$csrfStorage = new SessionTokenStorage($session);
$csrfManager = new CsrfTokenManager($csrfGenerator, $csrfStorage);

$formFactory = Forms::createFormFactoryBuilder()
    // ...
    ->addExtension(new CsrfExtension($csrfManager))
    ->getFormFactory();

为什么我在这里失踪?

1 个答案:

答案 0 :(得分:0)

经过几次头痛后,我终于找到了问题所在。这就是我session部分的config.yml部分的显示方式:

session:
    storage_id: session.storage.php_bridge
    handler_id: ~
    save_path:  ~

将上述配置更改为此配置:

session:
    handler_id: session.handler.native_file
    save_path:  ~

显然~根本没有设置默认handler_id