Symfony CSRF and Ajax

前端 未结 3 651
遥遥无期
遥遥无期 2020-12-01 00:25

I am trying to implement some ajax functionality in my Symfony 2 project. Using jquery\'s $.post I want to send some data back to my controller. However, when I just POST th

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 00:54

    I had this problem, intermittently. Turned out it was not due to my ajax, but because Silex gives you a deprecated DefaultCsrfProvider which uses the session ID itself as part of the token, and I change the ID randomly for security. Instead, explicitly telling it to use the new CsrfTokenManager fixes it, since that one generates a token and stores it in the session, such that the session ID can change without affecting the validity of the token.

    /** Use a CSRF provider that does not depend on the session ID being constant. We change the session ID randomly */
    $app['form.csrf_provider'] = $app->share(function ($app) {
        $storage = new Symfony\Component\Security\Csrf\TokenStorage\SessionTokenStorage($app['session']);
        return new Symfony\Component\Security\Csrf\CsrfTokenManager(null, $storage);
    });
    

提交回复
热议问题