Using CSRF protection with manual rendering

blackcat562
Member | 10
+
0
-

I need to have a lot of control on the rendering of my form so I am doing a manual render, but if I add: $form->addProtection('Expired') I get this error:

Nette\InvalidStateException
Cannot start session when headers already sent search►

367:        <?php $form->render('end') ?>

If I do a simple echo $form I don't get this error but obviously my form doesn't look right.

Any help will be highly appreciated. Thanks.

Last edited by blackcat562 (2019-04-06 21:37)

Milo
Nette Core | 1283
+
0
-

CSRF protection field needs to store secret in session. So, ensure session has been started before rendering such form.

blackcat562
Member | 10
+
0
-

Are you talking about Nette's Forms session? I can't find any info about sessions in the docs.

Last edited by blackcat562 (2019-04-08 18:47)

Ondřej Kubíček
Member | 494
+
0
-

general session, you have to start manualy as milo wrote
just add to config file:

session:
    autoStart: true
blackcat562
Member | 10
+
0
-

that makes sense, but as a beginner I have no idea where to add that, is that a yaml config file?

manwe
Member | 44
+
0
-

blackcat562 wrote:

that makes sense, but as a beginner I have no idea where to add that, is that a yaml config file?

Nette uses .neon ( https://ne-on.org/ ) config files, you'll for sure have at least the basic config.neon file, so you can put it there :)

Milo
Nette Core | 1283
+
0
-

@blackcat562 From another point of view… Where in your code you add protection field?

David Grudl
Nette Core | 8228
+
+7
-

Guys, @blackcat562 is using standalone forms. And it's really a challenge to solve this.

I think the simplies trick is to generate CSRF token before page rendering. Just change

$form->addProtection('Expired');

To:

$form->addProtection('Expired')->getToken();
blackcat562
Member | 10
+
0
-

Thanks @DavidGrudl that's just what I was looking for!