在application的config中可以开启csrf的设置
$config['csrf_protection'] = TRUE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();
$config['csrf_regenerate'] = TRUE;
当这个为true的话,每次提交都会生成新的token值和cookie值,就算刷新页面,其token值也不变,因为生成的token值,如果检测到cookie里有,就会读取cookie中的值,而不是重新生成。如果$config['csrf_regenerate'] = TRUE;最好提交的token值为从cookie中动态获取。
页面用:
$this->security->csrf_verify();
来设置csrf
而不需要在代码中验证csrf,因为系统input类会在构造函数中进行了验证。
core/Input.php中的构造函数如下:
public function __construct()
{
$this->_allow_get_array = (config_item('allow_get_array') !== FALSE);
$this->_enable_xss = (config_item('global_xss_filtering') === TRUE);
$this->_enable_csrf = (config_item('csrf_protection') === TRUE);
$this->_standardize_newlines = (bool) config_item('standardize_newlines');
$this->security =& load_class('Security', 'core');
// Do we need the UTF-8 class?
if (UTF8_ENABLED === TRUE)
{
$this->uni =& load_class('Utf8', 'core');
}
// Sanitize global arrays
$this->_sanitize_globals();
// CSRF Protection check
if ($this->_enable_csrf === TRUE && ! is_cli())
{
$this->security->csrf_verify();
}
log_message('info', 'Input Class Initialized');
}
所以,csrf是自动验证的。如果在代码中再调用一次:
$this->security->csrf_verify();
其结果就是报错,因为csrf_verify()会在第一次调用时清除POST中的token,所以再调用时,就出错了。
开启了系统的csrf验证,
$config['csrf_protection'] = TRUE;
那么在所有的post提交,都会在input中进行验证,所以就有这个参数:
$config['csrf_exclude_uris'] = array();
用来排除不需要验证的post提交。
所以,如果不想麻烦,就用自己的csrf,或者分离app,不同app不同配置。