Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate new CSRF token without reloading the entire form

Tags:

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.

like image 216
grzechoo Avatar asked Jul 13 '12 08:07

grzechoo


People also ask

How CSRF tokens are generated?

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.

How do I add a CSRF token?

To use it, just include @csrf in your forms to include the token field.

Does every form need CSRF token?

No, you just need to generate a token on a per-session basis.

Does CSRF token change?

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.


1 Answers

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 \Symfony\Component\Form\Extension\Csrf\CsrfProvider\SessionCsrfProvider $csrf */ $csrf = $this->get('form.csrf_provider'); $token = $csrf->generateCsrfToken($intention);   return new Response($token); 

Symfony 2.4

/** @var \Symfony\Component\Security\Csrf\CsrfTokenManagerInterface $csrf */ $csrf = $this->get('security.csrf.token_manager'); $token = $csrf->refreshToken($intention);  return new Response($token); 
like image 109
Vitalii Zurian Avatar answered Sep 19 '22 06:09

Vitalii Zurian