从不同的域-src iframe设置cookie

时间:2012-04-09 06:13:09

标签: php security iframe cookies cross-domain

以下是相关网页: http://www.customazon.com/demo

主页面(@ customazon.com)加载包含辅助域名的iframe(@ gamekeg.com)。我想允许用户使用提供的密码登录管理控制面板。问题是,由于它是第二个域,浏览器将其视为“第三方Cookie”,并且大多数人完全拒绝它们。我需要找到一种方法来允许在这个iframe中设置cookie。要求用户调整他们的cookie设置是选项。

我尝试过的事情:

  1. 在标题中设置P3P短版本(CP =字符串的许多不同版本): 标题('P3P:CP =“IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT”';

  2. 创建(可能不正确,但我尽力管理)带有policy.p3p和p3p.xml文件的P3P长版本。

  3. 一些奇怪的javascript加载一个隐藏的iframe并发布到它(Safari解决方法?)。

  4. 丝毫没有任何效果。可以给予任何帮助以找到允许这种方法的方法很棒。

1 个答案:

答案 0 :(得分:3)

(我可能已经在这个答案中改变了域名,但理论应该是相同的。)

您最好的选择是从gamekeg.com登录页面到customazon.com进行cross-domain AJAX request(您需要发送一些特殊标题以允许跨域请求 - 请阅读该链接的更多内容)。在正常情况下,除非你控制两个站点(你似乎),否则这是不可能的。

在gamekeg.com登录页面上,用户成功登录后,您可以拨打这样的电话:

// I don't expect you to use jQuery, but I don't recall the entire
// AJAX process off of the top of my head. You may have to set
// xhr.withCredentials = true or something.
$.ajax(
    "http://customazon.com/ajax_login.php",
    {
        "username": <?php echo $username; ?>,
        "password_hash": <?php echo $password_hash; ?>
    }
);

ajax_login.php可能类似于:

// Send appropriate cross-domain headers here.
// In addition, you must configure your crossdomain.xml in your root.
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: http://source.com");
header("Access-Control-Allow-Headers: Content-Type, *");
if (isset($_POST["username"]) && isset($_POST["password_hash"])) {
    setcookie("username", $_POST["username"], time() + 24 * 60 * 60);
    setcookie("password", $_POST["password_hash"], time() + 24 * 60 * 60);
}

然后,在框架容器上,您可以经常检查以查看用户是否已登录(readCookie取自QuirksMode):

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function checkAjaxLogin() {
    if (readCookie("username") !== null && readCookie("password")) {
        // You're logged in now; refreshing the page should
        // do the rest, assuming the cookies are named correctly.
        window.location.refresh();
    }
}

但是,如果您可以使用Flash,则可能会加快此过程,因为Flash请求不关心跨域策略。但是,我没有Flash的技巧来提供一个例子,反正可能还有很多。

相关问题