I am reading tutorial here
https://symfony.com/doc/current/form/csrf_protection.html
how to add csrf token. It says to use
form_end()
in the template. But this is not working, gives error:
Type error: Too few arguments to function Symfony\Component\Form\FormRenderer::renderBlock(), 0 passed in E:\projektai\php projektai\htdocs\mokomieji\symfony_4_demo\var\cache\dev\twig\bb\bb2248f7be504240fcc2ab43dabf593090ebc4c897ce72b1a979082d62914b47.php on line 48 and at least 2 expected
Here is answer which shows how to fix but it is only when you have form object built:
Symfony Type error: Too few arguments to function FormRenderer::renderBlock()
How to do this without having form object? Here is login from login documentation page:
{% if error %}
<div>{{ error.messageKey|trans(error.messageData, 'security') }}</div>
{% endif %}
<form action="{{ path('login') }}" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="_username" value="{{ last_username }}" />
<label for="password">Password:</label>
<input type="password" id="password" name="_password" />
<button type="submit">Login</button>
{{ form_end() }}
Place the field containing the CSRF token as early as possible within the HTML file. Place the field that contains the token before any non-hidden fields and before any places where user-controllable data is embedded.
Yes, using tokens is the only way to protect reliably against CSRF attacks. Whether a protection is required or not depends on the actions the program does with the submitted data. As a rule of thumb: If data is modified with the permissions or context of the current user, you need the protection.
Now that Security component will check for the CSRF token, you have to add a hidden field to the login form containing the CSRF token. By default, this field is named _csrf_token . That hidden field must contain the CSRF token, which can be generated by using the csrf_token function.
CSRF protection works by adding a hidden field to your form - called _token by default - that contains a value that only you and your user knows. This ensures that the user - not some other entity - is submitting the given data. Symfony automatically validates the presence and accuracy of this token.
You can use the helper twig function csrf_token
as described in the doc here, as example:
<input type="hidden" name="_csrf_token"
value="{{ csrf_token('authenticate') }}"
>
More help in this answer.
UPDATE:
Other strategy: pass from controller:
$tokenProvider = $this->container->get('security.csrf.token_manager');
$token = $tokenProvider->getToken('example')->getValue();
Hope this help
You can use {{ form_row(form._token) }}
to generate the required CSRF token field to your form render in Symfony 3 (i'm currenlty use this method with Symfony 3.4).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With