0

Zend Framework 2 formElement csrf 有问题。

它工作正常,直到我提交无效表单,点击同一页面然后刷新页面。字段上出现“notTheSame”验证错误,并显示消息“提交的表单不是来自预期的站点” 。这是正确的,因为如果我检查 csrf 字段的值,它与提交之前的值不同。

在我决定添加 csrf 字段之前,表单运行良好。

我正在创建我的 csrf 字段,如下所示:

class SignupForm extends Form
{
    public function __construct()
    {
        parent::__construct('signup');

        $this->setAttribute('method', 'post')
             ->setHydrator(new ClassMethodsHydrator(false))
             ->setInputFilter(new InputFilter());

        $this->add(array(
             'type' => 'Zend\Form\Element\Csrf',
             'name' => 'csrf',
             'options' => array(
             )
         ));

    // I also add a couple of fieldsets after this

在视图文件中:

<?php
$form = $this->form;
$form->setAttribute('action', $this->url('needfunding', array('action' => 'register')));
$form->setAttribute('class', "signup-form start");
$form->prepare();

echo $this->form()->openTag($form);
$applicant = $form->get('applicant');
?>      

<?php $this->FormErrors($form); ?>

<?php echo $this->formRow($form->get('csrf')); ?>

(FormErrors 是一个视图助手,用于检索表单消息并设置它们的样式)

在我的控制器中:

   public function signupAction()
    {       
        $form = new SignupForm();

        /* some unrelated code [...]  */            

        $request = $this->getRequest();

        if ($request->isPost()) {

            $category_group_id = $request->getPost()->category_group;

                $selected_categories = array();

                foreach ($categories as $c) { 
                    $selected_categories[$c->getId()]=html_entity_decode($c->getName());
                }

                $form->get('category')->setValueOptions($selected_categories);

            $form->setData($request->getPost());

            if ($form->isValid()) {

        /* some unrelated code [...]  */            

                return $this->redirect()->toRoute('signupconfirmation');
           }
           else {

           }
        }

        return array('form' => $form, 'categories' => $ordered_categories);
    }

我想我的问题是,为什么我的 csrf 会在我回到表单页面后重新生成,因为表单无效?

PS:我在这篇文章Zend Framework 2 CSRF Protection中找不到我的解决方案

4

1 回答 1

0

我遇到过类似的问题。就我而言,我使用的是带有Zend\Authentication\Validator\Authentication验证的登录表单。验证器在每次验证尝试时都会破坏会话,因为它使用的Zend\Authentication\AuthenticationService是默认Zend\Authentication\Storage\Session存储。因为 csrf 值存储在 session 中,使用验证器会破坏 scrf 值,因此必须在每次登录表单 POST 尝试时重新创建它。

所以,我的建议是:尝试检查会话是否在刷新期间没有被破坏(它不应该)。此参考可能会有所帮助: http: //framework.zend.com/manual/2.2/en/modules/zend.session.config.html

于 2013-10-11T15:11:14.173 回答