简体   繁体   中英

Symfony CSRF invalid token: Mismatch between token in URL and token in form

I want to implement a form in Symfony that filters a data set for me.

The extract of my twig file as well as the the FilterType that is used for the form are shown below.

list.html.twig

{% block filterContent %}
    {{ form_start(form) }}
        <div class="row">
            {#This renders a red banner if the form contains errors.#}
            {#If the form variable is not called "form", pass it explicitly.#}
            {% include 'Form/form_errors_banner.html.twig' with {'form': form} %}
            {{ form_row(form.component) }}
            {{ form_row(form._token) }}
            {{ form_errors(form) }}
        </div>

        <input type="reset" id="resetter" class="btn-primary btn btn-xs" value="{{ 'label.resetAll'|trans }}"/>
        <input type="submit" class="btn-primary btn btn-xs" value="{{ 'label.applyFilter'|trans }}"/>
    {{ form_end(form) }}
    <!-- <br clear="all" /> -->
{% endblock filterContent %}

FilterType.php

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->setAction($options['data']['url'])
        ->setMethod('GET')
        ->add('component', ChoiceType::class, array(
            'label'       => 'Component',
            'placeholder' => 'Select Component',
            'choices'     => array(
                'All'      => 'All',
                'Document' => 'Document',
                'User'     => 'User',
                'Waiver'   => 'Waiver'
            ),
            'required'    => false,
        ));
}

For some reason I get the following error message indicating that my CSRF token is invalid. CSRF invalid error message

After having a closer look into this, I suspect that the error is caused, because the CSRF token in the transmitted URL differs from the one that is sent with the form: CSRF token mismatch

I already tried to remove {{ form_row(form._token) }} line in my twig file and cleared my browser and server cache, but still the error message pops up.

Could anyone help me and tell me what I did wrong?

In FilterType.php, ensure that you are using the same ID for your token as in your twig form. You can customize it via configureOptions:

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'csrf_token_id' => FilterType::class
        ]);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM