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.
A CSRF token is a unique, secret, unpredictable value that is generated by the server-side application and transmitted to the client in such a way that it is included in a subsequent HTTP request made by the client.
To use it, just include @csrf in your forms to include the token field.
No, you just need to generate a token on a per-session basis.
CSRF tokens are often bound to the user's session: while the user is logged in, they keep the same CSRF token. However, there are some security advantages to changing the CSRF token more often, or even on every request.
Assuming that you use default CSRF Provider, in your AJAX controller you can get your CSRF Provider service and "ask" it to regenerate token:
/** @var \Symfony\Component\Form\Extension\Csrf\CsrfProvider\SessionCsrfProvider $csrf */ $csrf = $this->get('form.csrf_provider'); $token = $csrf->generateCsrfToken($intention); return new Response($token);
/** @var \Symfony\Component\Security\Csrf\CsrfTokenManagerInterface $csrf */ $csrf = $this->get('security.csrf.token_manager'); $token = $csrf->refreshToken($intention); return new Response($token);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With