Generate new CSRF token without reloading the entire form

后端 未结 4 2095
误落风尘
误落风尘 2020-12-01 06:55

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

相关标签:
4条回答
  • 2020-12-01 07:15

    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);
    
    0 讨论(0)
  • 2020-12-01 07:21

    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.

    0 讨论(0)
  • 2020-12-01 07:30

    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.

    0 讨论(0)
  • 2020-12-01 07:33

    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);
    
    0 讨论(0)
提交回复
热议问题