Symfony 4-如何在不构建表单的情况下添加csrf令牌? [英] Symfony 4 - how to add csrf token without building form?
问题描述
我在这里阅读教程
https://symfony.com/doc/current/form/csrf_protection.html
如何添加csrf令牌.它说要使用
how to add csrf token. It says to use
form_end()
模板中的
.但这不起作用,并给出错误:
in the template. But this is not working, gives error:
类型错误:函数参数太少Symfony \ Component \ Form \ FormRenderer :: renderBlock(),传入的0E:\ projektai \ phpprojektai \ htdocs \ mokomieji \ symfony_4_demo \ var \ cache \ dev \ twig \ bb \ bb \ bb2248f7be504240fcc2ab43dabf593090ebc4c897ce72b1a979082d62914b47.php在第48行,预计至少2个
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类型错误:函数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() }}
推荐答案
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') }}"
>
有关此答案的更多帮助.
更新:
其他策略:从控制器传递:
Other strategy: pass from controller:
$tokenProvider = $this->container->get('security.csrf.token_manager');
$token = $tokenProvider->getToken('example')->getValue();
希望获得帮助
这篇关于Symfony 4-如何在不构建表单的情况下添加csrf令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!