0

我为我的所有 ajax 调用使用了预定义的响应格式。

如果请求是,success那么服务器将响应:

{"status":true,"data":{"name":"person","age":2}}

请注意data不是必需的。

如果请求失败,那么我会得到

{"status":false,"reason":"You are not authorised."}

所以每个响应都有一个status字段,如果状态是FALSE那么就会有reason字段。

问题是现在我CSRF在 Codeigniter 中启用了保护,如果令牌过期/失败,系统输出

The action you have requested is not allowed.

这是 HTML 内容。

是否可以扩展安全类,这样如果请求是通过 Ajax 的,那么它将保持 json_encoded 格式,否则使用 html 格式。(我不想修改核心)

谢谢。

4

1 回答 1

2

此错误消息是从方法呈现的CI_Exceptions::show_error(位于系统/核心中)。您可以通过通常的方式扩展此类并覆盖此方法以捕获此错误并返回您想要的任何内容。

您可以通过覆盖它来摆脱CI_Security::csrf_show_error方法内部的调用,这样它就不会简单地调用

show_error('The action you have requested is not allowed.');

这可能更健壮。

CI_Exceptions或者,您可以在课堂内攻击这个。由于此错误不附带特定的错误代码,因此您必须匹配可能在更新之间中断的消息(当前是硬编码)。生成的类可能如下所示:

class MY_Exceptions extends CI_Exceptions {
    public function show_error($heading, $message, $template = 'error_general', $status_code = 500) {
        if ($message == 'The action you have requested is not allowed.') {
            // handle this error your way
        } else {
            // send every other error to the original handler
            parent::show_error($heading, $message, $template, $status_code);
        }
    }
}
于 2012-11-22T20:22:57.110 回答