所以这是对“我如何让 3rd 方 cookie 在 Safari 中工作”问题的第十次报复,但我再次问,因为我认为竞争环境已经改变,可能在 2012 年 2 月之后。获得第三名的标准技巧之一Safari 中的派对 cookie 如下:使用一些 javascript 发布到隐藏的 iframe。它(过去)欺骗 Safari 认为用户已经与第三方内容进行了交互,因此允许设置 cookie。
我认为这个漏洞已经在轻微丑闻之后被堵住了,据透露谷歌在其广告中使用了这一技巧。至少,在使用这个技巧时,我完全无法在 Safari 中设置 cookie。我发现了一些随机的互联网帖子,声称苹果正在努力填补漏洞,但我还没有找到任何官方消息。
作为后备方案,我什至尝试重新设计主要的第三方框架,以便您必须在内容加载之前单击一个按钮,但即使是那种程度的直接交互也不足以融化 Safari 冰冷的心。
那么有没有人确定 Safari 是否真的堵住了这个漏洞呢?如果是这样,是否还有其他解决方法(除了在每个请求中手动包含会话 ID)?
只是想在这里留下一个不需要用户交互的简单工作解决方案。
正如我在 post I made 中所述:
基本上,您需要做的就是在 top.location 上加载您的页面,创建会话并将其重定向回 facebook。
将此代码添加到您的 index.php
顶部并将 $page_url
设置为您的应用程序最终选项卡/应用程序 URL,您将看到您的应用程序可以正常运行。
<?php
// START SAFARI SESSION FIX
session_start();
$page_url = "http://www.facebook.com/pages/.../...?sk=app_...";
if (isset($_GET["start_session"]))
die(header("Location:" . $page_url));
if (!isset($_GET["sid"]))
die(header("Location:?sid=" . session_id()));
$sid = session_id();
if (empty($sid) || $_GET["sid"] != $sid):
?>
<script>
top.window.location="?start_session=true";
</script>
<?php
endif;
// END SAFARI SESSION FIX
?>
注意:这是为 facebook 制作的,但它实际上可以在任何其他类似情况下工作。
2012 年 12 月 20 日编辑 - 维护签名请求:
上面的代码不维护请求发布数据,并且您会丢失签名请求,如果您的应用程序依赖于签名请求,请随意尝试以下代码:
注意:这仍在正确测试中,可能不如第一个版本稳定。使用风险自负/感谢您提供反馈。
(感谢 CBroe 在这里为我指明了正确的方向,以便改进解决方案)
// Start Session Fix
session_start();
$page_url = "http://www.facebook.com/pages/.../...?sk=app_...";
if (isset($_GET["start_session"]))
die(header("Location:" . $page_url));
$sid = session_id();
if (!isset($_GET["sid"]))
{
if(isset($_POST["signed_request"]))
$_SESSION["signed_request"] = $_POST["signed_request"];
die(header("Location:?sid=" . $sid));
}
if (empty($sid) || $_GET["sid"] != $sid)
die('<script>top.window.location="?start_session=true";</script>');
// End Session Fix
你说你愿意让你的用户在内容加载之前点击一个按钮。我的解决方案是让一个按钮打开一个新的浏览器窗口。该窗口为我的域设置一个 cookie,刷新打开器,然后关闭。
因此,您的主脚本可能如下所示:
<?php if(count($_COOKIE) > 0): ?>
<!--Main Content Stuff-->
<?php else: ?>
<a href="/safari_cookie_fix.php" target="_blank">Click here to load content</a>
<?php endif ?>
然后 safari_cookie_fix.php 看起来像:
<?php
setcookie("safari_test", "1");
?>
<html>
<head>
<title>Safari Fix</title>
<script type="text/javascript" src="/libraries/prototype.min.js"></script>
</head>
<body>
<script type="text/javascript">
document.observe('dom:loaded', function(){
window.opener.location.reload();
window.close();
})
</script>
This window should close automatically
</body>
</html>
我用 .htaccess 欺骗了 Safari:
#http://www.w3.org/P3P/validator.html
<IfModule mod_headers.c>
Header set P3P "policyref=\"/w3c/p3p.xml\", CP=\"NOI DSP COR NID CUR ADM DEV OUR BUS\""
Header set Set-Cookie "test_cookie=1"
</IfModule>
它也停止了对我的工作。我所有的应用程序都在 Safari 中丢失会话并重定向到 Facebook。由于我急于修复这些应用程序,因此我目前正在寻找解决方案。我会及时向大家发布。
编辑(2012-04-06):显然Apple用5.1.4“修复”了它。我确信这是对 Google 事物的反应:“在执行其 cookie 政策时存在问题。如果 Safari 中的“阻止 Cookie”首选项设置为默认设置“第三方网站可以设置 cookie”来自第三方和广告商”。http://support.apple.com/kb/HT5190
对于我的具体情况,我通过使用 window.postMessage() 并消除了任何用户交互来解决问题。请注意,这仅在您可以在父窗口中以某种方式执行 js 时才有效。通过让它包含来自您的域的 js,或者如果您可以直接访问源。
在 iframe(域-b)中,我检查是否存在 cookie,如果未设置,则会向父级(域-a)发送 postMessage。例如;
if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1
&& document.cookie.indexOf("safari_cookie_fix") < 0) {
window.parent.postMessage(JSON.stringify({ event: "safariCookieFix", data: {} }));
}
然后在父窗口(域-a)中监听事件。
if (typeof window.addEventListener !== "undefined") {
window.addEventListener("message", messageReceived, false);
}
function messageReceived (e) {
var data;
if (e.origin !== "http://www.domain-b.com") {
return;
}
try {
data = JSON.parse(e.data);
}
catch (err) {
return;
}
if (typeof data !== "object" || typeof data.event !== "string" || typeof data.data === "undefined") {
return;
}
if (data.event === "safariCookieFix") {
window.location.href = e.origin + "/safari/cookiefix"; // Or whatever your url is
return;
}
}
最后在您的服务器 (http://www.domain-b.com/safari/cookiefix) 上设置 cookie 并重定向回用户来自的位置。下面的例子是使用 ASP.NET MVC
public class SafariController : Controller
{
[HttpGet]
public ActionResult CookieFix()
{
Response.Cookies.Add(new HttpCookie("safari_cookie_fix", "1"));
return Redirect(Request.UrlReferrer != null ? Request.UrlReferrer.OriginalString : "http://www.domain-a.com/");
}
}
"*"
添加到 PostMessage
以修复语法错误
在您的 Ruby on Rails 控制器中,您可以使用:
private
before_filter :safari_cookie_fix
def safari_cookie_fix
user_agent = UserAgent.parse(request.user_agent) # Uses useragent gem!
if user_agent.browser == 'Safari' # we apply the fix..
return if session[:safari_cookie_fixed] # it is already fixed.. continue
if params[:safari_cookie_fix].present? # we should be top window and able to set cookies.. so fix the issue :)
session[:safari_cookie_fixed] = true
redirect_to params[:return_to]
else
# Redirect the top frame to your server..
render :text => "<script>alert('start redirect');top.window.location='?safari_cookie_fix=true&return_to=#{set_your_return_url}';</script>"
end
end
end
redirect_to params[:return_to]
。需要根据要重定向到的安全位置白名单检查该参数。请参阅owasp.org/index.php/…
我遇到了同样的问题,今天我找到了一个适合我的修复程序。如果用户代理包含 Safari
并且未设置 cookie,我将用户重定向到 OAuth 对话框:
<?php if ( ! count($_COOKIE) > 0 && strpos($_SERVER['HTTP_USER_AGENT'], 'Safari')) { ?>
<script type="text/javascript">
window.top.location.href = 'https://www.facebook.com/dialog/oauth/?client_id=APP_ID&redirect_uri=MY_TAB_URL&scope=SCOPE';
</script>
<?php } ?>
在身份验证和请求权限之后,OAuth 对话框将重定向到我在顶部位置的 URI。所以设置cookies是可能的。对于我们所有的画布和页面选项卡应用程序,我已经包含了以下脚本:
<script type="text/javascript">
if (top.location.href==location.href) top.location.href = 'MY_TAB_URL';
</script>
因此,用户将再次被重定向到已设置有效 cookie 的 Facebook 页面选项卡,并再次发布已签名的请求。
我终于找到了与 Sascha 提供的解决方案类似的解决方案,但稍作调整,因为我在 PHP 中明确设置了 cookie:
// excecute this code if user has not authorized the application yet
// $facebook object must have been created before
$accessToken = $_COOKIE['access_token']
if ( empty($accessToken) && strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') ) {
$accessToken = $facebook->getAccessToken();
$redirectUri = 'https://URL_WHERE_APP_IS_LOCATED?access_token=' . $accessToken;
} else {
$redirectUri = 'https://apps.facebook.com/APP_NAMESPACE/';
}
// generate link to auth dialog
$linkToOauthDialog = $facebook->getLoginUrl(
array(
'scope' => SCOPE_PARAMS,
'redirect_uri' => $redirectUri
)
);
echo '<script>window.top.location.href="' . $linkToOauthDialog . '";</script>';
这样做是检查 cookie 在浏览器运行 safari 时是否可用。在下一步中,我们在应用程序域上,即上面作为 URL_WHERE_APP_IS_LOCATED 提供的 URI。
if (isset($_GET['accessToken'])) {
// cookie has a lifetime of only 10 seconds, so that after
// authorization it will disappear
setcookie("access_token", $_GET['accessToken'], 10);
} else {
// depending on your application specific requirements
// redirect, call or execute authorization code again
// with the cookie now set, this should return FB Graph results
}
因此,在重定向到应用程序域后,明确设置了一个 cookie,并将用户重定向到授权过程。
在我的情况下(因为我使用的是 CakePHP,但它应该可以与任何其他 MVC 框架一起正常工作)我再次调用登录操作,其中再次执行 FB 授权,这一次由于现有的 cookie 而成功。
授权该应用程序一次后,我在 Safari (5.1.6) 中使用该应用程序没有任何问题
希望这可以帮助任何人。
我在运行 iOS 的设备上遇到了这个问题。我使用 iframe 制作了一个可嵌入到普通网站的商店。不知何故,在每次页面加载时,用户都会获得一个新的 sessionid,导致用户在进程中途卡住,因为会话中不存在某些值。
我尝试了此页面上给出的一些解决方案,但弹出窗口在 iPad 上效果不佳,我需要最透明的解决方案。
我使用重定向解决了它。嵌入我的网站的网站必须首先将用户重定向到我的网站,因此顶部框架包含指向我的网站的 url,我在其中设置 cookie 并将用户重定向到嵌入我的网站的网站上的正确页面,即通过通过网址。
示例 PHP 代码
远程网站将用户重定向到
http://clientname.example.com/init.php?redir=http://www.domain.com/shop/frame
初始化文件
<?php
// set a cookie for a year
setcookie('initialized','1',time() + 3600 * 24 * 365, '/', '.domain.com', false, false);
header('location: ' . $_GET['redir']);
die;
用户最终在嵌入我的网站的 http://www.domain.com/shop/frame
上,按应有的方式存储会话并吃 cookie。
希望这可以帮助某人。
让我分享我在 ASP.NET MVC 4 中的修复。主要思想类似于 PHP 的正确答案。在靠近脚本部分的标题中的主布局中添加的下一个代码:
@if (Request.Browser.Browser=="Safari")
{
string pageUrl = Request.Url.GetLeftPart(UriPartial.Path);
if (Request.Params["safarifix"] != null && Request.Params["safarifix"] == "doSafariFix")
{
Session["IsActiveSession"] = true;
Response.Redirect(pageUrl);
Response.End();
}
else if(Session["IsActiveSession"]==null)
{
<script>top.window.location = "?safarifix=doSafariFix";</script>
}
}
此解决方案适用于某些情况 - 如果可能:
如果 iframe 内容页面使用包含 iframe 的页面的子域,则不再阻止 cookie。
谷歌实际上让这只猫从袋子里出来了。他们使用它来访问跟踪 cookie 有一段时间了。 Apple 几乎立即修复了它=\
这是我使用的一些代码。我发现如果我从我的网站设置任何 cookie,那么从那时起 cookie 就会在 iframe 中神奇地工作。
http://developsocialapps.com/foundations-of-a-facebook-app-framework/
if (isset($_GET['setdefaultcookie'])) {
// top level page, set default cookie then redirect back to canvas page
setcookie ('default',"1",0,"/");
$url = substr($_SERVER['REQUEST_URI'],strrpos($_SERVER['REQUEST_URI'],"/")+1);
$url = str_replace("setdefaultcookie","defaultcookieset",$url);
$url = $facebookapp->getCanvasUrl($url);
echo "<html>\n<body>\n<script>\ntop.location.href='".$url."';\n</script></body></html>";
exit();
} else if ((!isset($_COOKIE['default'])) && (!isset($_GET['defaultcookieset']))) {
// no default cookie, so we need to redirect to top level and set
$url = $_SERVER['REQUEST_URI'];
if (strpos($url,"?") === false) $url .= "?";
else $url .= "&";
$url .= "setdefaultcookie=1";
echo "<html>\n<body>\n<script>\ntop.location.href='".$url."';\n</script></body></html>";
exit();
}
PHP 中其他人发布的稍微简单的版本:
if (!isset($_COOKIE, $_COOKIE['PHPSESSID'])) {
print '<script>top.window.location="https://example.com/?start_session=true";</script>';
exit();
}
if (isset($_GET['start_session'])) {
header("Location: https://apps.facebook.com/YOUR_APP_ID/");
exit();
}
我已经找到了完美的答案,这要归功于一个叫艾伦的人,他值得在这里得到所有的赞誉。 (http://www.allannienhuis.com/archives/2013/11/03/blocked-3rd-party-session-cookies-in-iframes/)
他的解决方案简单易懂。
在 iframe 内容服务器(域 2)上,在根域级别添加一个名为 startsession.php 的文件,其中包含:
<?php
// startsession.php
session_start();
$_SESSION['ensure_session'] = true;
die(header('location: '.$_GET['return']));
现在在包含 iframe (domain1) 的顶级网站上,对包含 iframe 的页面的调用应如下所示:
<a href="https://domain2/startsession.php?return=http://domain1/pageWithiFrame.html">page with iFrame</a>
就是这样!简单的:)
这样做的原因是因为您将浏览器定向到第三方 URL,因此在 iframe 中显示来自它的内容之前告诉它信任它。
我使用了修改后的(在链接中添加了signed_request 参数)Whiteagle 的技巧,它在 safari 中运行良好,但在这种情况下 IE 会不断刷新页面。所以我对 Safari 和 Internet Explorer 的解决方案是:
$fbapplink = 'https://apps.facebook.com/[appnamespace]/';
$isms = stripos($_SERVER['HTTP_USER_AGENT'], 'msie') !== false;
// safari fix
if(! $isms && !isset($_SESSION['signed_request'])) {
if (isset($_GET["start_session"])) {
$_SESSION['signed_request'] = $_GET['signed_request'];
die(header("Location:" . $fbapplink ));
}
if (!isset($_GET["sid"])) {
die(header("Location:?sid=" . session_id() . '&signed_request='.$_REQUEST['signed_request']));
}
$sid = session_id();
if (empty($sid) || $_GET["sid"] != $sid) {
?>
<script>
top.window.location="?start_session=true";
</script>
<?php
exit;
}
}
// IE fix
header('P3P: CP="CAO PSA OUR"');
header('P3P: CP="HONK"');
.. later in the code
$sr = $_REQUEST['signed_request'];
if($sr) {
$_SESSION['signed_request'] = $sr;
} else {
$sr = $_SESSION['signed_request'];
}
我也一直被这个问题困扰,但终于得到了解决方案,最初直接在浏览器中加载 iframe url,就像小弹出窗口一样,然后只访问 iframe 内的会话值。
Safari 现在会阻止所有第三方 cookie。您只能使用 Storage API 尝试让用户访问他们的第三方 cookie。
https://www.infoq.com/news/2020/04/safari-third-party-cookies-block/
我在现有答案中没有明确说明的一些上下文(自 2012 年以来也发生了很多变化!):
如果您可以同时控制第 3 方 iframe 和父页面(即您能够在父页面上插入 JavaScript),那么有几种解决方法可用。我建议其中最优雅的是使用@Frank 的回答所描述的 postMessage API,因为 a) 这不需要任何重定向,b) 不需要任何用户交互。
如果您不能同时控制第 3 方 iframe 和父页面,例如,您在不受控制的网站上托管了一个小部件,那么此处发布的大多数答案在 Safari as of May 2020 中都不起作用,并且将stop working in Chrome around 2022。也就是说,除非用户已经访问过您的域或与 iframe 交互,否则您无法设置 cookie。但是,有一些商业服务提供解决此问题的解决方案,例如 CloudCookie.io
我最近在 Safari 上遇到了同样的问题。我想出的解决方案是基于 Local Storage HTML5 API。使用本地存储,您可以模拟 cookie。
这是我的博文,其中包含详细信息:http://log.scalemotion.com/2012/10/how-to-trick-safari-and-set-3rd-party.html
我决定一起摆脱 $_SESSION
变量 &围绕 memcache 编写了一个包装器来模拟会话。
检查https://github.com/manpreetssethi/utils/blob/master/Session_manager.php
用例:用户登陆应用程序的那一刻,使用 Session_manager 存储签名的请求,并且由于它在缓存中,因此您以后可以在任何页面上访问它。
注意:这在 Safari 中私密浏览时不起作用,因为每次重新加载页面时 session_id 都会重置。 (愚蠢的野生动物园)
您可以通过将标头添加为 p3p 策略来解决此问题。我在 safari 上遇到了同样的问题,因此在文件顶部添加标头后解决了我的问题。
<?php
header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
?>
不定期副业成功案例分享