绕开新版Chrome针对iFrame跨域Cookie的限制
众所周知,谷歌Chrome在80以上版本默认了SameSite=Lax设置,导致iFrame无法跨域读写Cookie内容。 网上的解决方法大同小异,都是换成Https协议并修改SameSite=None配置,但笔者需要保留Http方式。
笔者原来的鉴权方法(新版Chrome已经失效):
<?php function AuthCode() {
if (!filter_var($_SERVER['REMOTE_ADDR'], 275, 4194304|8388608)) return;
$token = $_REQUEST['token'] ?: $_COOKIE['token'];
$tkn = explode('|', $token); $skey = $tkn[0]; $sign = $tkn[1];
if ($sign!=md5("{$skey}/salt")) {http_response_code(403); exit;}
if ($_REQUEST['token']) setcookie('token',$token,time()+31536000,'/');
} AuthCode(); ?>
笔者利用localStorage绕开限制的鉴权方法:
<?php function AuthCode() {
if (!filter_var($_SERVER['REMOTE_ADDR'], 275, 4194304|8388608)) return;
$token = $_REQUEST['token'] ?: $_COOKIE['token'];
$tkn = explode('|', $token); $skey = $tkn[0]; $sign = $tkn[1];
if ($sign==md5("{$skey}/salt") && $_REQUEST['token']) {
echo "<script>localStorage.setItem('token','{$token}')</script>";
}
if ($sign!=md5("{$skey}/salt")) {
echo "<script>var token = localStorage.getItem('token'); ";
echo "if (token) document.cookie = 'token='+token+'; ";
echo "expires=Thu, 1 Jan 2099 0:0:0 GMT; path=/'</script>";
exit(PHP_EOL."<script>if (token) location.reload()</script>");
}
} AuthCode(); ?>