简体   繁体   English

Symfony2 CSRF形式,令牌无效

[英]Symfony2 csrf forms, token invalid

EDIT: There is a Tl;Dr at the end... 编辑:最后有一个Tl; Dr ...

I keep getting CSRF errors while using symfony2 and auto generated forms. 使用symfony2和自动生成的表单时,我不断收到CSRF错误。

Here's my controller: (new is called to display form, create is called on submit) 这是我的控制器:(调用new来显示表单,调用create时提交)

public function newAction($guru)
{

    //Make the Entity Manager
    $em = $this->getDoctrine()
            ->getEntityManager();
    $guru = $em->getRepository('TSNStatsBundle:Guru')
            ->findOneById($guru);
    //If the guru id exists        
    if ($guru)
    {
        $alert = new Alert();
        //Create default values
        $time = new \DateTime(2012-12-30);
        $time->setTime(23,59);

        //Set default times to "none available (23:59)"
        $alert->setText($time)
        ->setEmail($time)
        ->setTwitter($time)
        ->setChat($time)
        ->setGuru($guru);

        //Make the form, set types, 
        $formBuilder = $this->createFormBuilder($alert);


         $formBuilder->add('buy', 'checkbox', array(
                    'required' => false
                ))
                ->add('date', 'date', array(
                    'input' => 'datetime',
                    'widget' => 'single_text'
                ))
                ->add('stock', new StockType());
        if ($guru->getInstantAlerts() ==1)
        {
            if ($guru->getText() == 1)
            {
                $formBuilder->add('text', 'time', array(
                       'input' => 'datetime',
                       'widget' => 'text',

                   ));
            }
            if ($guru->getEmail() == 1)
            {
                $formBuilder->add('email', 'time', array(
                       'input' => 'datetime',
                       'widget' => 'text',

                   ));
            }
            if ($guru->getTwitter() == 1)
            {
                $formBuilder->add('twitter', 'time', array(
                       'input' => 'datetime',
                       'widget' => 'text',

                   ));
            }
            if ($guru->getChat() == 1)
            {
                $formBuilder->add('chat', 'time', array(
                       'input' => 'datetime',
                       'widget' => 'text',

                   ));
            }
        }
        $formBuilder->add('size')
                ->add('short', 'checkbox', array(
                    'required' => false
                ))
                ->add('his')
                ->add('guru');
         $form = $formBuilder->getForm();



        return $this->render('TSNStatsBundle:Buy:new.html.twig', array(
            'form' => $form->createView(),
            'guru' => $guru
        ));



    }
    else
    {
        //your guru ain't real bro!
    }
    return $this->render('TSNStatsBundle:Buy:new.html.twig', array(
        'alert' => $alert,
        'form' => $form->createView(),
        'guru' => $guru->getName()

     ));
}

public function createAction()
{
    $alert = new Alert();

    $form = $this->createForm(new AlertType(), $alert);
    $request = $this->getRequest();
    if ($this->getRequest()->getMethod() == 'POST') {
        $form ->bind($request);


        if ($form->isValid())
        {
            $em = $this->getDoctrine()
                    ->getEntityManager();
            $em->persist($alert);
            $em->flush();

            return $this->redirect($this->generateUrl('new_alert', array(
                'guru' => 2
            ) ));

        }
    }

    return $this->render('TSNStatsBundle:Buy:errors.html.twig', array(
          'errors' => $form->getErrors()
    ));

}

Here's my template: 这是我的模板:

Adding entry for {{ guru }}
<form action="{{ path('create_alert' ) }}" method="post" {{ form_enctype(form) }} class="alert">
{{ form_widget(form) }}
<p>
    <input type="submit" value="Submit">
</p>
</form>

As far as I can tell, everything is by the book. 据我所知,一切都是由书决定的。 A _token value IS in every form every time I refresh, the widget it getting called, so all parts should be there... 每次刷新时,_token值都会以每种形式出现,它会调用它的小部件,因此所有部分都应该存在。

Thanks, 谢谢,

EDIT: when I replace my whole form creation process with: 编辑:当我将整个表单创建过程替换为:

$form = $this->createForm(new AlertType(), $alert);

then it works again. 然后它再次起作用。 The problem is the logic I want doesn't belong in a "type" class. 问题是我想要的逻辑不属于“类型”类。 That and the fact that the way I'm doing it SHOULD work right? 那以及我做事的方式应该正确吗? Could it have anything to do with the way I'm adding elements to my form? 它可以与我向表单中添加元素的方式有关吗? That's the only thing I see different about my build vs. a createForm() build. 对于我的构建与createForm()构建,这是我唯一看到的不同之处。

Tl;Dr: Using a createForm call with an *entity*Type call works fine, creating my own form using createFormBuilder() gets met with a CSRF error on every submit.... Same _token is used for both. Tl; Dr:使用带有* entity * Type调用的createForm调用可以很好地工作,使用createFormBuilder()创建我自己的表单在每次提交时都会遇到CSRF错误。...相同的_token用于两者。

也许使用这个可以帮助您:

{{form_widget(form._token)}}

Try substituting 尝试替代

{{ form_widget(form) }}
{{ form_rest(form) }}

For 对于

{{ form_widget(form) }}

You can pass the same $options array like in the form type, to a FormBuilder, and you can turn csrf protection off this way: 您可以将相同的$ options数组(如表单类型)传递给FormBuilder,然后可以通过以下方式关闭csrf保护:

$this->createFormBuilder($object, $options = array(
    'csrf_protection' => false,
));

Original example: http://symfony.com/doc/current/book/forms.html#csrf-protection 原始示例: http : //symfony.com/doc/current/book/forms.html#csrf-protection

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM