我通过 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") }}">
但我不太确定是否足以激活此保护。
我的 Controller 与文档上的形式相同,所以它看起来像这样:
<?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") }}
的隐藏输入就足够了或者我必须在 Controller 中添加一些东西?
最佳答案
我发现 @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 保护。
关于php - Symfony2,登录表单 - CSRF 保护,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19360146/