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
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);
Yes, the bot could fetch an csrf token and post something to the form, but as the token is bound to the session, it doesn't matter. CSRF tokens are not intended to prevent submission of forms by bots.
To me the easier solution is to redirect user on the same form, passing data alredy inserted via POST.
In that way the token will be generated again in an automatic way.
Moreover, you'll not lost data input.
Use this to regenerate CSRF token (Since Symfony2.4):
$csrf = $this->get('security.csrf.token_manager'); //Symfony\Component\Security\Csrf\CsrfTokenManagerInterface
$token = $csrf->refreshToken($intention); // Intention is specified in form type
return new Response($token);