如何通过 Twig 模板在 Silex 2 中使用 CSRF 令牌?

How to use CSRF token in Silex 2 via Twig template?

我已经注册了一个 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答案的解读)

控制器:

$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(FormServiceProvide ins silex 世界)的 Forms 并且没有像

这样的形式树枝助手
<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.:

此时您可以创建自己的树枝助手等等,或者 只需使用

$tokenId = 'intention'; 
$csrf_token = $app['csrf.token_manager']->getToken($tokenId);

然后将 $csrf_token 变量传递给你的树枝视图并以

这样的形式使用它

当然,检查 given/submitted 令牌是否有效 - 您每次提交带有 csrf-token 的表单时的工作(请参阅 Silex 的 CSRF 文档的使用部分)