Php – Zend Framework 2 CSRF Protection

csrfphpzend-frameworkzend-framework2

Currently I try to use the CSRF Protection of the Zend Framework 2.

But everytime I send my form, I got this error message:

The form submitted did not originate from the expected site

I have implemeted the CSRF Protection in this way:

1) created a Form Class and added the csrf:

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

2) echoed the csrf element in the view file:

 echo $this->form()->openTag($forgotPasswordForm);
 echo $this->formRow($forgotPasswordForm->get('email'));
 echo $this->formRow($forgotPasswordForm->get('secret'));
 echo $this->formSubmit($forgotPasswordForm->get('submit'));
 echo $this->form()->closeTag($forgotPasswordForm);

I figured out that the csrf token isn't stored in the session, but why?

Best Solution

I had this line in my Controller:

$forgotPasswordForm = new ForgotPassword();
$forgotPasswordForm->prepare();

I moved $forgotPasswordForm->prepare() to the view file and now it works :-)

Thank you for your support!