Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
684 views
in Technique[技术] by (71.8m points)

symfony - Generate new CSRF token without reloading the entire form

If a user gets logged out (due to session expiration or for other reasons) in the background while using my Symfony2 application, I have implemented a JS layer appearing on the screen, allowing the user to log back in immediately and continue using the website.

The problem is, if the user is in the middle of filling a form and gets logged out, after logging back in using the JS layer, he's still looking at the same form with values he already managed to type in, but his session changes. The CSRF token in the form is therefore invalid.

Is there a way to generate a new CSRF token based on the current session and particular form, grab it by AJAX and replace in the form? Or maybe there is other solution to this?

I don't want to disable the CSRF protection.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Assuming that you use default CSRF Provider, in your AJAX controller you can get your CSRF Provider service and "ask" it to regenerate token:

Symfony 2.3 (and prior)

/** @var SymfonyComponentFormExtensionCsrfCsrfProviderSessionCsrfProvider $csrf */
$csrf = $this->get('form.csrf_provider');
$token = $csrf->generateCsrfToken($intention); 

return new Response($token);

Symfony 2.4

/** @var SymfonyComponentSecurityCsrfCsrfTokenManagerInterface $csrf */
$csrf = $this->get('security.csrf.token_manager');
$token = $csrf->refreshToken($intention);

return new Response($token);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...