如何在symfony中禁用csrf?

时间:2017-11-12 13:56:32

标签: php forms symfony csrf

我使用下面的代码,它也有csrf。但是如何禁用其csrf?我搜索了Disable CSRF token on login form并没有帮助,因为我的情况下没有使用createFormBuilder(),所以该怎么办?

$csrfStorage = new NativeSessionTokenStorage();
$csrfGenerator = new UriSafeTokenGenerator();
$csrfManager = new CsrfTokenManager($csrfGenerator, $csrfStorage);

$formFactory = Forms::createFormFactoryBuilder()
    ->addExtension(new CsrfExtension($csrfManager))
    ->getFormFactory();


$defaultFormTheme = 'bootstrap_3_layout.html.twig';

$vendorDir = realpath(__DIR__.'/../vendor');
$appVariableReflection = new \ReflectionClass('\Symfony\Bridge\Twig\AppVariable');
$vendorTwigBridgeDir = dirname($appVariableReflection->getFileName());
$viewsDir = realpath('twig');

$twig = new Twig_Environment(new Twig_Loader_Filesystem(array(
    $viewsDir,
    $vendorTwigBridgeDir.'/Resources/views/Form',
)));
$formEngine = new TwigRendererEngine(array($defaultFormTheme), $twig);
$twig->addRuntimeLoader(new \Twig_FactoryRuntimeLoader(array(
    TwigRenderer::class => function () use ($formEngine, $csrfManager) {
        return new TwigRenderer($formEngine, $csrfManager);
    },
)));
$twig->addExtension(new FormExtension());

$translator = new Translator('en');
$twig->addExtension(new TranslationExtension($translator));
$form = $formFactory->createBuilder()
    ->add('task', TextType::class)
    ->add('dueDate', DateType::class)
    ->getForm();

$request = Request::createFromGlobals();
$form->handleRequest();
if ($form->isSubmitted() && $form->isValid()) {
    $data = $form->getData();
    print_r($data);
}

$twig->display('new.html.twig', array(
    'form' => $form->createView(),
));

1 个答案:

答案 0 :(得分:1)

$form = $formFactory->createBuilder('Symfony\Component\Form\Extension\Core\Type\FormType', null,  array('csrf_protection' => false))