2017-01-23 123 views
0

表單提交,驗證並將表單數據保存到服務器時,如何在Symfony2/3中更改csrf標記?在提交表單和驗證表單後更改CSRF令牌

// AppController.php 
... 
public function saveAction(Request $request) { 
    $event = new Data(); 
    $form = $this->createForm(DataForm::class, $event); 
    $form->handleRequest($request); 
    if ($form->isSubmitted() && $form->isValid()) { 
     $creator = $this->getDoctrine() 
      ->getRepository('AppBundle:User') 
      ->find($this->getUser()->getId()); 
     $event->setCreator($creator); 
     $entityManager = $this->getDoctrine()->getManager(); 
     $entityManager->persist($event); 
     $entityManager->flush(); 

<的東西在這裏改變CSRF令牌。有任何想法嗎? >

 return $this->redirect($this->generateUrl('event_view', ['id' => $event->getId()])); 
    } 
    $message = ['text' => 'Wrong data to save', 'type' => 'danger']; 
    $this->get('session')->set('messages', [$message]); 
    return $this->redirect($this->generateUrl('event_create')); 
} 
... 

回答

1

應當令牌自動再生CSRF。我能想到的,你可能想這樣做,如果你使用Ajax和提交表單是唯一的原因,無論是什麼原因需要得到下一個標記: 在你的表單類型:

public function setDefaultOptions(OptionsResolverInterface $resolver) 
{ 
    $resolver->setDefaults(array(
     //...other defaults 
     'intention'  => 'data_form_intention', 
    )); 
} 

在你saveAction:

$csrf = $this->get('security.csrf.token_manager');  
$token = $csrf->refreshToken("data_form_intention"); 
+0

OptionsResolverInterface已棄用。我使用了_'csrf_token_id'_類的OptionsResolver,而不是_'intention'_。謝謝。是工作 – chrisperk