CI - Set CSRF Hash and Cookie

/**
     * Set CSRF Hash and Cookie
     *
     * @return    string
     */
    protected function _csrf_set_hash()
    {
        if ($this->_csrf_hash === NULL)
        {
            // If the cookie exists we will use its value.
            // We don't necessarily want to regenerate it with
            // each page load since a page could contain embedded
            // sub-pages causing this feature to fail
            if (isset($_COOKIE[$this->_csrf_cookie_name]) && is_string($_COOKIE[$this->_csrf_cookie_name])
                && preg_match('#^[0-9a-f]{32}$#iS', $_COOKIE[$this->_csrf_cookie_name]) === 1)
            {
                return $this->_csrf_hash = $_COOKIE[$this->_csrf_cookie_name];
            }

            $rand = $this->get_random_bytes(16);
            $this->_csrf_hash = ($rand === FALSE)
                ? md5(uniqid(mt_rand(), TRUE))
                : bin2hex($rand);
        }

        return $this->_csrf_hash;
    }

    令牌(tokens)默认会在每一次提交时重新生成,或者你也可以设置成在 CSRF cookie 的生命周期内一直有效。———— 有安全隐患吧。 这样会减少服务器的负荷.

       默认情况下令牌重新生成提供了更严格的安全机制,但可能会对 可用性带来一定的影响,因为令牌很可能会变得失效(例如使用浏览器的返回前进按钮、 使用多窗口或多标签页浏览、异步调用等等)。你可以修改下面这个参数来改变这一点。

      $config['csrf_regenerate'] = TRUE;  //这种情况下,每次提交表单后,都会重新生成token。(1) 重复提交一个页面会失败。(2)用浏览器的返回前进按钮,会因为令牌不一致出错。—— 生成了新的令牌值,而“后退”过去的那个页面不刷新的话,依然使用的是旧的令牌值!
       将其设置为false即可。
      $config['csrf_expire'] = 7200;    
      $config['csrf_regenerate'] = false;
 

 

posted @ 2016-07-12 12:01  1678924929  阅读(239)  评论(0编辑  收藏  举报