我正在尝试创建一个跨多个域(由我控制)的登录。我的策略是,在成功登录响应后,我发出 CORS 请求以获取每个其他所需域的 cookie。返回 cookie 后,我重定向到用户的主页(可能在任何域上)
如果我注释掉重定向,我发现一切正常:所有 CORS cookie 都已设置,并且我在其他域中登录。但是,当我重定向时,有时不会设置 CORS cookie。这是我在客户端的代码的总体思路:
// This is running client side when the user visits "A.com/index.html"
// PLEASE NOTE: the distinction between A.com and B.com is important
$.post('https://A.com/attemptLogin', function(data) {
if (!data.success) { return; }
var token = data.loginToken;
var userURL = data.userURL; // userURL may be in A.com or B.com...
// now get a cookie at the alternate domain B.com
$.ajax({
url: 'http://B.com/getDomainCookie/' + token,
method: 'GET',
xhrFields: { withCredentials: true },
success: function() {
// if I comment out the next line, the cookie is always set successfully
// if I leave the line in, it is hit or miss whether the cookie is set.
location.href = userURL;
}
});
});
我的猜测是ajax回调是在浏览器完成设置cookie之前触发的,可能与它是一个B.com cookie有关,而这段代码是在A.com上运行的。
感谢任何帮助。这是我发布的第一个问题,因此也感谢对问题礼仪和格式的建设性批评!
最佳答案
我加入了 50 毫秒的延迟 window.setTimeout(function() { location.href='';}, 50);
让它有一点空闲时间来存储到 cookie。另一方面,在隐身窗口中似乎根本不起作用,会丢弃所有 CORS cookie。
关于javascript - 等待在 location.href 重定向之前设置 CORS cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45039896/