无需重新加载整个表单即可生成新的 CSRF 令牌 [英] Generate new CSRF token without reloading the entire form

查看:24
本文介绍了无需重新加载整个表单即可生成新的 CSRF 令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果用户在使用我的 Symfony2 应用程序时在后台注销(由于会话过期或其他原因),我已经在屏幕上实现了一个 JS 层,允许用户立即重新登录并继续使用网站.

If a user gets logged out (due to session expiration or for other reasons) in the background while using my Symfony2 application, I have implemented a JS layer appearing on the screen, allowing the user to log back in immediately and continue using the website.

问题是,如果用户正在填写表单并被注销,在使用 JS 层重新登录后,他仍在查看具有他已经设法输入的值的同一个表单,但是他的会话更改.因此表单中的 CSRF 令牌无效.

The problem is, if the user is in the middle of filling a form and gets logged out, after logging back in using the JS layer, he's still looking at the same form with values he already managed to type in, but his session changes. The CSRF token in the form is therefore invalid.

有没有办法根据当前会话和特定表单生成一个新的CSRF令牌,通过AJAX抓取它并在表单中替换?或者也许有其他解决方案?

Is there a way to generate a new CSRF token based on the current session and particular form, grab it by AJAX and replace in the form? Or maybe there is other solution to this?

我不想禁用 CSRF 保护.

I don't want to disable the CSRF protection.

推荐答案

假设您使用默认的 CSRF Provider,在您的 AJAX 控制器中,您可以获取您的 CSRF Provider 服务并要求"它重新生成令牌:

Assuming that you use default CSRF Provider, in your AJAX controller you can get your CSRF Provider service and "ask" it to regenerate token:

/** @var \Symfony\Component\Form\Extension\Csrf\CsrfProvider\SessionCsrfProvider $csrf */
$csrf = $this->get('form.csrf_provider');
$token = $csrf->generateCsrfToken($intention); 

return new Response($token);

<小时>

Symfony 2.4

/** @var \Symfony\Component\Security\Csrf\CsrfTokenManagerInterface $csrf */
$csrf = $this->get('security.csrf.token_manager');
$token = $csrf->refreshToken($intention);

return new Response($token);

这篇关于无需重新加载整个表单即可生成新的 CSRF 令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆