显然,我想强制在登录表单中设置CSRF令牌。假设我没有在登录表单中添加CSRF令牌,而且我已经提交了表单。此时,我的请求是,必须将响应返回为拒绝,以便我不添加CSRF令牌。
我怎么能这样做,或者我可以这样做吗?
你当然可以。您只需创建并输出CSRF令牌:
<input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}">
通常这就是你所需要的,因为https://github.com/symfony/security/blob/master/Http/Firewall/SimpleFormAuthenticationListener.php#L59-L60会自动检查令牌。您需要将_csrf_token
作为字段名称和authenticate
作为标记名称。
您可以根据需要对其进行个性化设置:
# app/config/security.yml
security:
# ...
firewalls:
secured_area:
# ...
form_login:
# ...
csrf_parameter: YOUR_csrf_token
csrf_token_id: YOUR_authenticate
小心!自4.2起,此表单登录侦听器已弃用。以下是建议使用gurad https://symfony.com/doc/current/security/form_login_setup的示例。
干杯!
您可以在Controller
中注入CsrfTokenManagerInterface并在登录方法中使用它,如以下示例所示:
SecurityController.php
class SecurityController extends Controller
{
/** @var CsrfTokenManagerInterface */
private $tokenManager;
public function __construct(CsrfTokenManagerInterface $tokenManager = null)
{
$this->tokenManager = $tokenManager;
}
/**
* @Route("/login", name="login")
*
* @param Request $request
*/
public function login(Request $request)
{
// Get the login error if exists
$error = $this->get('security.authentication_utils')->getLastAuthenticationError();
// Last username entered by user
$lastUsername = $this->get('security.authentication_utils')->getLastUsername();
$csrfToken = $this->tokenManager
? $this->tokenManager->getToken('authenticate')->getValue()
: null;
if (null === $csrfToken) {
//your exception
}
return $this->renderLogin([
'last_username' => $lastUsername,
'error' => $error,
'csrf_token' => $csrfToken
]);
}
}