我通过Symfony2 security documentation获得此登录表单,其中包含以下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") }}">
,但我不确定,是否足以激活此保护。
我的控制器与doc上的格式相同,所以它看起来像这样:
<?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") }}
的隐藏输入,或者我必须在控制器中添加一些东西吗?
答案 0 :(得分:2)
我发现@Chris McKinnel的答案不正确。现在,Symfony2在教程页面上有这一部分:
http://symfony.com/doc/current/cookbook/security/csrf_in_login_form.html
我需要在 security.yml 中添加行:
form_login:
# ...
csrf_provider: form.csrf_provider
并改变这个
<input type="hidden" name="_token" value="{{ csrf_token("intention") }}">
到
<input type="hidden" name="_csrf_token" value="{{ csrf_token("authenticate") }}">
现在我确信我的身份验证表格受CSRF保护。
答案 1 :(得分:1)
默认情况下启用CSRF保护,因此您只需在HTML中呈现CSRF令牌即可。您无需在控制器中执行任何操作。
您有几个选择:
要么工作正常。