问题的原因是执行 AJAX 调用时会话 cookie 轮换,CodeIgniter 3 中包含正确的修复方法
您有四个选择:
Cope:我自己以前也遇到过这个问题,但不知道其确切原因。简而言之,我保存了每个 XMLHttpRequest 的 Promise,如果遇到 HTTP 状态代码 401,客户端应用程序将以弹出窗口的形式请求凭据,然后重试 AJAX Promise。
使用 jQuery 的客户端,只需添加以下 ajaxError 处理程序:
$(document).ajaxError(function (e, xhr, settings, exception) {
if (xhr.status == 401)
{
// open your popup
$('#login-popup').modal('open');
// attach the xhr object to the listener
$(document).bind( "retry-xhr", {
xhro: xhr
},
function( event ) {
// retry the xhr when fired
$.ajax( event.data.xhro );
});
}
});
当您重新登录时,只需调用此命令即可重试您的请求:
$(document).trigger('retry-xhr');
服务器端,你只需要在你的构造函数中添加一个if
if (!$this->session->userdata('logged_in') && $this->input->is_ajax_request())
{
$this->output->set_status_header('401');
exit;
}
这很有用,因为有些用户会让他们的 Web 应用程序窗口整夜打开,会话超时就会开始。然后用户会打电话给我,说无法执行任何 AJAX 功能,我必须告诉他们按 F5
附注如果在 Angular 上,我已成功使用 HTTP 身份验证拦截器模块
Hack:请参阅这篇文章,他的解决方案是在 ci_session 表中创建另一个字段并检查两个 cookie,因此您的会话在轮换后仍然有效。
它还详细解释了导致此故障的原因
http://www.hiretheworld.com/blog/tech-blog/codeigniter-session-race-conditions
Upgrade:开始使用已修复的下一个版本:
https://github.com/EllisLab/CodeIgniter/tree/release/3.0
Patch替换 system/libraries/Session.php 中的第 346 行(函数 sess_update())
if (($this->userdata['last_activity'] + $this->sess_time_to_update) >= $this->now)
With:
if (($this->userdata['last_activity'] + $this->sess_time_to_update) >= $this->now || $this->CI->input->is_ajax_request())