我已经注册了一个CsrfServiceProvider()
$app->register(new Silex\Provider\CsrfServiceProvider());
我的表格:
<form action="{{ url('some.action') }}" method="post">
<input type="text" name="blah-blah" value="" placeholder="">
<input type="hidden" name="_csrf_token" value="">{# how to output SCRF token here? #}
<button type="submit" class="btn btn-success">Submit</button>
感谢您的帮助!
解决方案(我对 V-Light 答案的解释)
Controller :
$app->get('/', function() use ($app) {
$tokenId = 'intention';
$csrf_token = $app['csrf.token_manager']->getToken($tokenId);
return $app['twig']->render('home.twig', [
'csrf_token' => $csrf_token,
]);
})->bind('home');
模板:
<input type="hidden" name="_csrf_token" value="{{ csrf_token }}">
最佳答案
我假设您不使用 symfony 的 Forms
(FormServiceProvide ins silex world),并且没有类似的表单 twig-helpers
<input type="hidden" name="_csrf_token" value="{{- csrf_token('intention') -}}">
但是无论如何先尝试,也许我的假设不正确并且它已经起作用了:)
FormServiceProvider
尝试安装Forms for Silex
然后看Usage documentaion-block of CSRF for Silex
When the CSRF Service Provider is registered, all forms created via the Form Service Provider are protected against CSRF by default.
所以这是不言自明的;)你应该做的唯一一件事 - 使用 FormServiceProvider 创建表单(请参阅文档)并在 twig 中正确呈现它们,而不是自己编写普通的旧 html。
但是...
You can also use the CSRF protection even without using the Symfony Form component.:
此时,您可以创建自己的 Twig 助手等,或者 只需使用
$tokenId = 'intention';
$csrf_token = $app['csrf.token_manager']->getToken($tokenId);
然后将 $csrf_token
变量传递给您的 twig-view 并以如下形式使用它
当然,检查给定/提交的 token 是否有效 - 每次使用 csrf-token 提交表单时您的工作(请参阅 Silex 的 CSRF 文档的使用部分)
关于symfony - 如何通过 Twig 模板在 Silex 2 中使用 CSRF token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44046111/