业务描述
- 从www.a.com 单点登录到 www.b.com
- 需要把setCookie 设置起
关键点
- 前端: 需要设置xhrFields 的 withCredentials: true
- 后端:
header("Access-Control-Allow-Credentials:true"); // 添加允许跨域设置cookie
header("Access-Control-Allow-Origin:" . 'www.b.com'); // 允许www.b.com 跨域访问
- 如果用axios的话, 不需要加xhrFields, 直接添加 withCredentials: true 属性即可
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<iframe
style="width:1000px;height:1000px"
src="http://www.a.com/home"
sandbox="allow-scripts allow-same-origin allow-popups"
>
</iframe>
<script>
$(document).ready(function(){
$.ajax({
url: "http://www.a.com/login",
type: "POST",
xhrFields: {
withCredentials: true
},
crossDomain: true,
data:{
'username': 'username',
'password': 'NjY2NjY2',
}
});
});
</script>
<?php
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
// 白名单
$allow_origin = array(
'b.com',
);
$domain = "";
foreach ($allow_origin as $key) {
if (strstr($origin, $key)) {
$domain = $origin;
}
}
if (!empty($domain)) {
header("Access-Control-Allow-Credentials:true"); // 添加允许跨域设置cookie
header("Access-Control-Allow-Origin:" . $domain);
header("Access-Control-Allow-Methods:POST,GET");
header("Access-Control-Allow-Headers:x-requested-with,content-type");
header("Cache-control:private");
header("X-Powered-By:zjx.com");
header("P3P: CP=CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR");
}