Symfony 1.4:在窗体中为CSRF定制错误消息 [英] Symfony 1.4: Custom error message for CSRF in forms

查看:167
本文介绍了Symfony 1.4:在窗体中为CSRF定制错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以告诉我在Symfony 1.4中的表单中如何自定义CSRF令牌错误消息。我使用sfDoctrineGuard进行登录,特别是在这种形式下,无论何时会话用完,并且您仍然打开页面,它都会引发非用户不友好的错误:检测到CSRF攻击。就像此会话已过期,请返回主页并再试一次听起来更好。



在表单类中执行此操作的正确方法是什么?

p>

谢谢。

解决方案

唯一的方法似乎是覆盖 sfForm :: addCSRFProtection()



/lib/form/BaseForm.class.php 你可以添加这段代码:

  class BaseForm extends sfFormSymfony 
{
public function addCSRFProtection($ secret = null)
{
parent :: addCSRFProtection($ secret);
if(array_key_exists(self :: $ CSRFFieldName,$ this-> getValidatorSchema())){
$ this-> getValidator(self :: $ CSRFFieldName) - > setMessage('csrf_attack' ,'此会话已过期,请返回主页并重试。');



code
$ b

在调用父方法之后,您检索与CSRF字段关联的验证程序,并更改代码 csrf_attack 的消息。

编辑:您还需要检查验证程序是否存在。有些表单可能会禁用它们的CSRF保护!



希望这有助于您!


Can anyone tell me where/how to customise the CSRF token error message for forms in Symfony 1.4. I'm using sfDoctrineGuard for logins and in this form particularly, whenever a session runs out and you still have the page open, it throws a very user-unfriendly error: "CSRF attack detected". Something like "This session has expired. Please return to the home page and try again" sounds better.

What's the right way to do this in the form class?

Thanks.

解决方案

The only way seems to be to overwrite sfForm::addCSRFProtection().

In /lib/form/BaseForm.class.php you can add this piece of code:

class BaseForm extends sfFormSymfony
{
    public function addCSRFProtection($secret = null)
    {
        parent::addCSRFProtection($secret);
        if (array_key_exists(self::$CSRFFieldName, $this->getValidatorSchema())) {
            $this->getValidator(self::$CSRFFieldName)->setMessage('csrf_attack', 'This session has expired. Please return to the home page and try again.');
        }
    }
}

After calling the parent method, you retrieve the validator associated with the CSRF field and change the message for the code csrf_attack.

Edit: You also need to check whether or not the validator exists. Some forms might have their CSRF protection disabled!

Hope this helps!

这篇关于Symfony 1.4:在窗体中为CSRF定制错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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