How is it possible to avoid validating CsrfToken in each method of the controller? ( Symfony 5 )

I created some forms, and added a csrf tokens to each, like this:

<input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}" />

I just found out, that folks use different token name for each form, and then validate them in a method of a controller, like this:

<input type="hidden" name="_csrf_token" value="{{ csrf_token('my_form_one') }}" />

 

public function processForm(Request $request): Response
{
    $token = $request->request->get("token");

    if (!$this->isCsrfTokenValid('my_form_one', $token))
    {
        // Error
    }

    // Process form
}

It looks like a lot of code bloat and repetition, to check a token for each post request at the beginning of each method of my controller. Is it possible to automate csrf validation somehow?

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *