在表单提交,验证并将表单数据保存到服务器时,如何更改Symfony2 / 3中的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'));
}
...
答案 0 :(得分: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");