JSON请求中的CodeIgniter CSRF令牌 [英] CodeIgniter CSRF token in JSON request

查看:205
本文介绍了JSON请求中的CodeIgniter CSRF令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了CodeIgniter/CSRF/JSON的问题.

I ran into an issue with CodeIgniter / CSRF / JSON.

我正在使用Content-Type"application/json向我的PHP后端发送http POST请求.有效负载是JSON数据.我将数据与CSRF令牌一起传递,该令牌已生成并存储在CSRF cookie中.标准的POST FORM请求,效果很好,但是当以JSON发送时失败.

I am sending http POST requests to my PHP backend with the Content-Type "application/json. The payload is JSON data. Along with the data, I pass the CSRF token that is generated and stored in the CSRF cookie. With a standard POST FORM request, it works just fine, but when sending as JSON it fails.

由于$ _POST数组由于JSON内容类型而为空,因此CodeIgniter无法验证cookie并引发错误.

As $_POST array is empty because of the JSON content-type, CodeIgniter fails to validate the cookie and throws an error.

我如何让CodeIgniter检查JSON有效负载并验证我的CSRF令牌?

How can I have CodeIgniter check JSON payload and validate my CSRF token ?

推荐答案

要解决该问题,我必须更改位于"system/core/"中的"Security.php"文件的代码.

To fix that issue, I had to change the code of the "Security.php" file located in "system/core/".

在函数"csrf_verify"中,替换该代码:

In function "csrf_verify", replace that code:

// Do the tokens exist in both the _POST and _COOKIE arrays?
if ( ! isset($_POST[$this->_csrf_token_name], $_COOKIE[$this->_csrf_cookie_name]))
{
$this->csrf_show_error();
}
// Do the tokens match?
if ($_POST[$this->_csrf_token_name] != $_COOKIE[$this->_csrf_cookie_name])
{
$this->csrf_show_error();
}

通过该代码:

// Do the tokens exist in both the _POST and _COOKIE arrays?
if ( ! isset($_POST[$this->_csrf_token_name], $_COOKIE[$this->_csrf_cookie_name])) {
    // No token found in $_POST - checking JSON data
    $input_data = json_decode(trim(file_get_contents('php://input')), true); 
    if ((!$input_data || !isset($input_data[$this->_csrf_token_name], $_COOKIE[$this->_csrf_cookie_name])))
        $this->csrf_show_error(); // Nothing found
    else {
        // Do the tokens match?
        if ($input_data[$this->_csrf_token_name] != $_COOKIE[$this->_csrf_cookie_name])
            $this->csrf_show_error();
    }
}
else {
    // Do the tokens match?
    if ($_POST[$this->_csrf_token_name] != $_COOKIE[$this->_csrf_cookie_name])
        $this->csrf_show_error();
}

该代码首先检查$ _POST,然后如果未找到任何内容,则检查JSON有效负载.

That code first checks $_POST then if nothing has been found, it checks the JSON payload.

执行此操作的理想方法是检查传入请求的Content-Type标头值.但是令人惊讶的是,这样做并非直截了当...

The ideal way of doing this would be to check the incoming request Content-Type header value. But surprisingly, it's not straight forward to do ...

如果有人有更好的解决方案,请在此处发布.

If someone has a better solution, please post it here.

欢呼

这篇关于JSON请求中的CodeIgniter CSRF令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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