Creating forms manually in Symfony2, but still use its CSRF and isValid() functionalily

后端 未结 4 1370
南旧
南旧 2020-12-29 07:22

OK, I googled this hard, but everything I find talks about Symfony forms in context of regular Symfony form processing (e.g. form_widget(), creating FormType class, etc.). I

相关标签:
4条回答
  • 2020-12-29 07:43

    I have seen that this is resolved but I have some form troubles too and saw an other post here :

    symfony2 CSRF invalid

    And their solution seems to me better than making my own token :

    There is no problem using {{ form_widget(form) }} to build your custom form. All you have to do is add the _token like this: {{ form_widget(form._token) }}

    0 讨论(0)
  • 2020-12-29 07:44

    Note: intention is no longer default to be unknown. When I checked this out in symfony 2.3, it would appear it to default to the type name:

    $options['intention'] ?: ($builder->getName() ?: get_class($builder->getType()->getInnerType()))

    It would be good if there was some programatic way to get the intention out that is used instead of having to rely on these defaults.

    0 讨论(0)
  • 2020-12-29 07:52

    My solution using Symfony 2.8:

    in the action Controller (when the form is submitted):

        $theToken = $request->get('Token');
    
        //Token Verification   
        $isValidToken = $this->isCsrfTokenValid('your_intention', $theToken);
        if ($isValidToken === false)
        {
            // Error
        }
    

    check this page where I found the info: http://api.symfony.com/2.8/Symfony/Component/Form/Extension/Csrf/CsrfProvider/CsrfProviderInterface.html#method_isCsrfTokenValid

    0 讨论(0)
  • 2020-12-29 07:57

    I think you're mismatching the intention here (argument passed to your CSRF provider). I tried generating form as you wrote above and break-pointed the generation of token. The value was unknown.

    So, try passing unknown instead of form to your generateCsrfToken call and hopefully it should work. ;)

    EDIT:

    I have just finished some digging and it now does make perfect sense.

    Look at the class FormTypeCsrfExtension. Apparently, it's the default extension used for CSRF token protection. On the line #80 (might not be this one exactly in your case) there is method setDefaultOptions that is usually overridden in your form types. Anyhow, there is a default options called intention that has a value of unknown ==> the one we are seeing here.

    My guess is that you could easily override this option in your own form type just by passing intention and setting your own value (just as you would pass csrf_protection => false when you would want to disable CSRF protection altogether).

    0 讨论(0)
提交回复
热议问题