2020-04-21 iframe 跨域单点登录

业务描述

  1. www.a.com 单点登录到 www.b.com
  2. 需要把setCookie 设置起

关键点

  1. 前端: 需要设置xhrFields 的 withCredentials: true
  2. 后端:
    header("Access-Control-Allow-Credentials:true"); // 添加允许跨域设置cookie
    header("Access-Control-Allow-Origin:" . 'www.b.com'); // 允许www.b.com 跨域访问
  3. 如果用axios的话, 不需要加xhrFields, 直接添加 withCredentials: true 属性即可

前端代码 (www.b.com)

<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>

后端代码 (www.a.com)

<?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");
        }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。