【问题标题】:How to set session.cookie value httponly in Codeigniter如何在 Codeigniter 中设置 session.cookie 值 httponly
【发布时间】:2014-08-17 10:53:46
【问题描述】:

我正在使用 Codeigniter 框架进行开发,我必须在我的应用程序上应用一些安全性。我希望我的 cookie 具有通过一些配置更改在整个应用程序中应用的 httponly 属性。我在我的应用程序/配置文件中做了以下更改

$config['cookie_secure']    = TRUE;
$config['cookie_httponly'] = TRUE;

我已经为我的 php.ini 文件设置了更改

ini_set( 'session.cookie_httponly', 1 );

在上述更改之后,我可以看到本地服务器上的 cookie 属性更改为 httponly,但是当我在实时服务器上部署应用程序时,它不起作用。我无法理解我需要应用哪些其他更改。

【问题讨论】:

    标签: php codeigniter cookies


    【解决方案1】:

    httpponly cookie 由启用 https 的网站(如 https://www.samplewebsite.com)支持,您无需手动设置。只需要求您的服务提供商将“cookie_httponly”值更改为 true,或者如果您有服务器访问权限,请自行设置。您还可以将以下代码应用于您的 .htaccess 文件。

    Header edit Set-Cookie ^(.*)$ $1;Secure;HttpOnly
    Header set Set-Cookie "%{http_cookie}e; HTTPOnly" env=http_cookie   
    

    【讨论】:

    • 这个答案中的两行对我不起作用,但第一行本身就可以。
    【解决方案2】:

    我在这里遇到了类似的问题,答案很简单。您需要修改其中一个CodeIgniter系统库system/libraries/Session.php中的一个函数,如下:

    /**
    * Write the session cookie
     *
     * @access  public
     * @return  void
     */
    function _set_cookie($cookie_data = NULL)
    {
        if (is_null($cookie_data))
        {
            $cookie_data = $this->userdata;
        }
    
        // Serialize the userdata for the cookie
        $cookie_data = $this->_serialize($cookie_data);
    
        if ($this->sess_encrypt_cookie == TRUE)
        {
            $cookie_data = $this->CI->encrypt->encode($cookie_data);
        }
        else
        {
            // if encryption is not used, we provide an md5 hash to prevent userside tampering
            $cookie_data = $cookie_data.md5($cookie_data.$this->encryption_key);
        }
    
        $expire = ($this->sess_expire_on_close === TRUE) ? 0 : $this->sess_expiration + time();
    
        // Set the cookie
        setcookie(
                    $this->sess_cookie_name,
                    $cookie_data,
                    $expire,
                    $this->cookie_path,
                    $this->cookie_domain,
                    $this->cookie_secure,
                    true// <-- SYSTEM LIBRARY MODIFICATION TO SET httpOnly to true!!
                );
    }
    

    上面的函数 _set_cookie() 需要一个额外的参数来强制所有的 cookie 都是 HTTP Only。 您可能可以扩展这个库并添加新版本的函数(推荐),但为了简单起见,我只是在这里对其进行了硬编码。

    【讨论】:

    • 我已经完成了更改,它在我的本地开发环境中显示 httponly cookie,但在生产环境中没有运气。另外我想知道它是否依赖于站点类型,即 http 还是 https 并且可能与 https 一起使用?
    • 我刚刚发现并知道上述设置只有在您的应用程序处于 ssl 部署即 https 时才有效
    • 这是什么版本的 CI? CI 3 似乎不是最新的
    猜你喜欢
    • 2012-05-18
    • 1970-01-01
    • 2020-03-19
    • 2011-04-01
    • 1970-01-01
    • 2015-07-21
    • 2020-01-18
    • 2017-01-30
    相关资源
    最近更新 更多