用于 csrf 保护的 Codeigniter 3 SameSite 属性

Pan*_*arn 2 codeigniter codeigniter-3

我有相互进行 CORS 调用的应用程序。2020 年 4 月的 Google 将需要 SameSite cookie = none。https://www.chromestatus.com/feature/5633521622188032

由于 chrome 80+ 版本,所有使用 chrome 浏览器的用户都会影响这个 csrf 错误。如何在使用 PHP 7.3 的 Codeigniter 框架上解决这个问题

在此处输入图片说明

小智 7

我有同样的问题,但我的 PHP 7.2 和我的 CI 3.X。通过对applications / config / config.php文件进行以下更改解决了该问题

$config['cookie_prefix']    = '';
$config['cookie_domain']    = ''; 
$config['cookie_path']      = '/; SameSite=None';
$config['cookie_secure']    = TRUE;
$config['cookie_httponly']  = FALSE;
Run Code Online (Sandbox Code Playgroud)

  • 只是警告,该技术在 PHP 7.3 中不起作用,因为它将开始转义 cookie 路径中的分号。可能想看看/sf/answers/3287992851/ (2认同)

小智 5

切勿修改 SYSTEM 目录中的文件,因为更新 codeigniter 时可能会出现问题。最好在 中APPLICATION/CORE创建一个名为的文件MY_Security.php并扩展安全控制器。

例子:

<?php defined('BASEPATH') OR exit('No direct script access allowed');

class MY_Security extends CI_Security {

    /**
     * CSRF Set Cookie with samesite
     *
     * @codeCoverageIgnore
     * @return  CI_Security
     */
    public function csrf_set_cookie()
    {
        $expire = time() + $this->_csrf_expire;
        $secure_cookie = (bool) config_item('cookie_secure');

        if ($secure_cookie && ! is_https())
        {
            return FALSE;
        }
        
        setcookie($this->_csrf_cookie_name,
                  $this->_csrf_hash,
                  ['samesite' => 'Strict',
                   'secure'   => true,
                   'expires'  => $expire,
                   'path'     => config_item('cookie_path'),
                   'domain'   => config_item('cookie_domain'),
                   'httponly' => config_item('cookie_httponly')]);
        
        log_message('info', 'CSRF cookie sent');

        return $this;
    }
}
Run Code Online (Sandbox Code Playgroud)