Symfony 2 Add CSRF Token when using a form without a class

后端 未结 3 519
情歌与酒
情歌与酒 2020-12-19 06:10

Firstly I\'m a complete noobie with Symfony 2. The question sounds simple, if I try and put some context into why and how I need this it will start to get confusing.

<
相关标签:
3条回答
  • 2020-12-19 06:18

    In (my) normal circumstances you create a form and do not specifically configure CSRF - it happens automatically, and you use form_rest(form) or form_end(form) to render the hidden input with CSRF token. I do not believe that this is any different for a form not backed by a model.

    0 讨论(0)
  • 2020-12-19 06:18

    I think what you are looking for is the following :

    This will render a CSRF token. Use this function if you want CSRF protection without creating a form

    {{ csrf_token("intention") }}
    

    For example:

    <a href="{{ path('remove_stuff', {token: csrf_token('intention')}) }}">Remove</a>
    

    source

    To validate this token from a controller, you can do:

    if ($this->get('token') !== $this->get('security.csrf.token_manager')->getToken('intention')->getValue()) {
        throw new \Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException('Invalid CSRF token');
    }
    

    To simplify check the token on Symfony 2.6 or newer

    if ($this->isCsrfTokenValid('intention', $submittedToken)) {
        // ... do something, like deleting an object
    }  
    
    0 讨论(0)
  • 2020-12-19 06:31

    Connection between Form Type and token:

    {{ csrf_token("task_item_intention") }}
    

    and in Form Type:

    class TaskType extends AbstractType
    {
    // ...
    
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class'      => 'Acme\TaskBundle\Entity\Task',
            'csrf_protection' => true,
            'csrf_field_name' => '_token',
            // a unique key to help generate the secret token
            'intention'       => 'task_item_intention',
        ));
    }
    
    // ...
    }
    
    0 讨论(0)
提交回复
热议问题