Using CSRF protection with manual rendering

6 months ago

blackcat562
Member | 7
+
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)

6 months ago

Milo
Nette Core | 1150
+
0
-

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

6 months ago

blackcat562
Member | 7
+
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)

6 months ago

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

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

session:
    autoStart: true

6 months ago

blackcat562
Member | 7
+
0
-

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

6 months ago

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 :)

6 months ago

Milo
Nette Core | 1150
+
0
-

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

6 months ago

David Grudl
Nette Core | 6877
+
+6
-

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();

6 months ago

blackcat562
Member | 7
+
0
-

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