我通过Symfony2 安全文档获得了这个登录表单,其中包含以下 TWIG 模板内容:
<form action="{{ path('login_check') }}" method="post">
<div class="input form">
<label for="username">Account name or E-mail:</label>
<input type="text" id="username" name="_username" value="{{ last_username }}" required="required" />
</div>
<div class="input form">
<label for="password">Password:</label>
<input type="password" id="password" name="_password" required="required" />
</div>
<input type="hidden" name="_token" value="{{ csrf_token("intention") }}">
<button type="submit">Log In</button>
</form>
我想以这种形式添加 CSRF 保护。如您所见,我添加了这一行<input type="hidden" name="_token" value="{{ csrf_token("intention") }}">
,但我不确定是否足以激活此保护。
我的控制器具有与文档相同的形式,所以它看起来像这样:
<?php
// src/Acme/SecurityBundle/Controller/SecurityController.php;
namespace Acme\SecurityBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
class SecurityController extends Controller
{
public function loginAction()
{
$request = $this->getRequest();
$session = $request->getSession();
// get the login error if there is one
if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
$error = $request->attributes->get(
SecurityContext::AUTHENTICATION_ERROR
);
} else {
$error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
$session->remove(SecurityContext::AUTHENTICATION_ERROR);
}
return $this->render(
'AcmeSecurityBundle:Security:login.html.twig',
array(
// last username entered by the user
'last_username' => $session->get(SecurityContext::LAST_USERNAME),
'error' => $error,
)
);
}
}
所以只需粘贴一个带有值的隐藏输入就足够了,{{ csrf_token("intention") }}
或者我必须在控制器中添加一些东西?