• 如何实现跨域cookie共享


    一、 背景

           为什么需要实现跨域共享cookie, 比如追踪用户的身份,根据特定用户进行推送或推荐。

    二、 Cookie共享的几种方案

    • 通过中间域名,比如a.example.com 和 b.example.com 可通过cookie.example.com 或 *.example.com 来实现cookie共享;
    • 通过CORS (cross origin resource sharing)跨域读取cookie, 参考。 

                  

    • 通过多域写cookie, image tag 方式,在其他域内种植上和当前域相同的cookie

             

                    

                     

    三、 几种方案对比

    方案 优点 缺点
    中间域名 无需前端改造 仅适用于二级域名相同的跨域共享。对已经存在的项目如严格依赖当前域名,不能有多次跳转比如a->b->a 是不合适的
    CORS 读 少量的前端适配 CORS读取后,当前页需要一次自刷新来重新发送cookie
    image tag 写 后端无感知

    前端适配及网络IO (需要从其他域获取cookie信息),页面会有顿挫感,

    对写cookie的时机有要求

    四、 CORS方式读取cookie code snippet

     1     function addCrossCookie() {
     2         var getCookie = "http://your.cross.domain/get_cookie";
     3         $.ajax({
     4                    type: "get",
     5                    url: getCookie,
     6                    dataType: "text",
     7                    mode: "cors",
     8                    crossDomain: true,
     9                    xhrFields: {
    10                        withCredentials: true
    11                    },
    12                    success: function(output) {
    13                    /*
    14                     * if cookie existed under `your.cross.domain`, you can answer it back by `output`.
    15                     * then document.cookie set it to `current.domain`
    16                     * window.location.reload to trigger a browser tab refresh to take the cross cookie to your backend.
    17                     */
    18                        document.cookie = output;
    19                        setTimeout(function() {
    20                            window.location.reload();
    21                        }, 0);
    22                    },
    23                    error: function(output) {
    24                        console.log(output);
    25                    }
    26                });
    27     }
  • 相关阅读:
    轻量级通用上采样算子-CARAFE
    图像分割-Mask Scoring R-CNN
    对C#Chart控件使用整理
    C#中的三种timer
    C#的三大难点
    将Excel的数据导入DataGridView中(转)
    状态者设计模式
    C# 中 DataTable 使用详解。
    Excel连接字符串在.NET中的应用
    状态机设计思想
  • 原文地址:https://www.cnblogs.com/sinsonglew/p/14264891.html
Copyright © 2020-2023  润新知