【发布时间】:2018-07-16 11:48:03
【问题描述】:
注意:这个问题不是关于失败的 AJAX 请求,而是关于失败的常规表单提交。
我在 CodeIgniter 3 中启用了 CSRF 保护,使用以下config.php:
$config['csrf_protection'] = TRUE;
$config['csrf_token_name'] = 'csrf_token_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
我在表单字段中正确使用了form_open(),以便自动生成包含 CSRF 令牌的所需隐藏字段。但是,当我在我的网站上提交任何表单时,它会导致“遇到错误 - 不允许您请求的操作”。错误。
Cookie 设置:
$config['cookie_prefix'] = '';
$config['cookie_domain'] = '';
$config['cookie_path'] = '/';
$config['cookie_secure'] = FALSE;
$config['cookie_httponly'] = FALSE;
会话设置:
$config['sess_driver'] = 'database';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 2592000; // one month in seconds
$config['sess_save_path'] = 'ci_sessions';
$config['sess_match_ip'] = TRUE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
此外,与大多数关于 CI CSRF 保护的问题相反,我的 AJAX 请求中的 CSRF 令牌确实可以通过将以下 sn-p 添加到我的初始 JavaScript 中正常工作:
function getCookie(c_name) { // A javascript function to get the cookie value
if(document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if(c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if(c_end == -1) c_end = document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}
$.ajaxPrefilter(function(options, originalOptions, jqXHR){ // This function will attach "csrf_test_name" with all the request you are sending.
if (options.type.toLowerCase() === "post") { // Required only if its a post method
var csrf_token = getCookie("csrf_cookie_name");
// initialize `data` to empty string if it does not exist
options.data = options.data || "";
// add leading ampersand if `data` is non-empty
options.data += options.data?"&":"";
// add _token entry
options.data += "csrf_token_name=" + csrf_token;
}
});
有什么方法可以让我的 CSRF 保护在表单字段中发挥作用?另外,我在 cookie 中的 csrf_cookie_name 值与隐藏的 HTML 字段中的 csrf_token_name 值不同,这应该发生吗?
【问题讨论】:
标签: php forms codeigniter csrf codeigniter-3