【问题标题】:Set-Cookie is not working in Chrome and Dolphin - with two websitesSet-Cookie 在 Chrome 和 Dolphin 中不起作用 - 有两个网站
【发布时间】:2020-12-11 17:43:00
【问题描述】:

请参阅 8 个月前的 this question and answer。答案解决了一段时间的问题,但今天我发现登录和注销对于我的每个网站(域)在 Chrome 和 Dolphin 中再次单独工作。 但是,在 Firefox、Edge 和 Opera 中一切正常。 这些浏览器中的其他域名的 cookie 是否发生了变化?我该如何修复它,以便在两个网站上同时登录和注销?

用户登录或注销或注册一个网站,我希望他们也自动登录或注销另一个网站,它适用于 Firefox、Edge 和 Opera。但是 Chrome 和 Dolphin 的用户,目前如果他们登录或退出一个网站,不会影响另一个网站。

Django 视图代码为:

@csrf_exempt
def set_session(request):
    """
    Cross-domain authentication.
    """
    response = HttpResponse('')
    origin = request.META.get('HTTP_ORIGIN')
    if isinstance(origin, bytes):
        origin = origin.decode()
    netloc = urlparse(origin).netloc
    if isinstance(netloc, bytes):
        netloc = netloc.decode()
    valid_origin = any(netloc.endswith('.' + site.domain) for site in Site.objects.all().order_by("pk"))
    if (not (valid_origin)):
        return response
    if (request.method == 'POST'):
        session_key = request.POST.get('key')
        SessionStore = import_module(django_settings.SESSION_ENGINE).SessionStore
        if ((session_key) and (SessionStore().exists(session_key))):
            # Set session cookie
            request.session = SessionStore(session_key)
            request.session.modified = True
        else:
            # Delete session cookie
            request.session.flush()
    response['Access-Control-Allow-Origin'] = origin
    response['Access-Control-Allow-Credentials'] = 'true'
    return response

JavaScript 代码是:

window.speedy = {};

window.speedy.setSession = function (domain, key) {
    $.ajax({
        url: '//' + domain + '/set-session/',
        method: 'post',
        data: {
            key: key
        },
        xhrFields: {
            withCredentials: true
        }
    });
};

然后有一段 JavaScript 代码调用了这个函数两次:

speedy.setSession('speedy.net', 'session_key');
speedy.setSession('speedymatch.com', 'session_key');

其中'session_key' 替换为用户的会话密钥。

和 Django 设置(使用 Django 3.0.6):

SESSION_COOKIE_SECURE = True
SESSION_COOKIE_SAMESITE = None

CSRF_COOKIE_SECURE = True
CSRF_COOKIE_SAMESITE = 'Strict'

这个问题有什么解决办法吗?我认为这是由于 Chrome 和 Dolphin 浏览器最近发生的变化。

我检查并从控制台收到以下错误:

看起来与以下链接有关:

【问题讨论】:

    标签: javascript django google-chrome cookies dolphin-browser


    【解决方案1】:

    一个 cookie ... 设置时没有 `SameSite` 属性。

    从 2020 年 7 月 14 日开始,您应该设置这些 1,2 并升级到 Django 3.1 3,4(8 月 4 日发布):

    SESSION_COOKIE_SECURE = True
    SESSION_COOKIE_SAMESITE = 'None'
    

    说明

    在 Django 3.1 之前,如果设置为 None 单例,则不会设置 samesite 属性:

    if samesite:
        if samesite.lower() not in ('lax', 'strict'):
            raise ValueError('samesite must be "lax" or "strict".')
        self.cookies[key]['samesite'] = samesite
    

    从 Django 3.1 开始,samesite 属性设置为 'None' 字符串;仍然不是None/False:

    if samesite:
        if samesite.lower() not in ('lax', 'none', 'strict'):
            raise ValueError('samesite must be "lax", "none", or "strict".')
        self.cookies[key]['samesite'] = samesite
    

    参考文献

    1. Cookies default to SameSite=Lax - Chrome Platform Status
    2. Reject insecure SameSite=None cookies - Chrome Platform Status
    3. Settings | Django documentation | Django #std:setting-SESSION_COOKIE_SAMESITE
    4. Allowed setting SameSite cookies flags to 'None' · Pull Request #11894 · django/django

    【讨论】:

    • 谢谢。我在 Django [code.djangoproject.com/ticket/31933] 上创建了一个问题并要求向后移植。我不想在问题code.djangoproject.com/ticket/31864 修复之前升级 Django(至少在 2020 年 9 月)。
    • 我也担心不兼容的客户端。 chromium.org/updates/same-site/incompatible-clients
    • 无论如何,我希望仅在 2020 年 10 月左右将 Django 升级到 3.1.*。我希望他们重新考虑他们的决定并同意将其向后移植到 Django
    • 我想如果它在生产中有效,我可以接受这个答案。我将使用 Django 的分叉版本 (-e git://github.com/speedy-net/django.git@3.0.9a#egg=django)。它适用于大多数用户吗?您建议如何处理不兼容客户端的用户?
    • 我做到了,它在生产中与 Chrome 一起工作(使用我创建的 fork)。但它不适用于我手机上的 Dolphin 和 Chrome(Chrome 之前也无法使用)。但它确实解决了桌面版 Chrome 的问题。
    猜你喜欢
    • 2020-04-05
    • 2018-11-03
    • 2017-07-19
    • 2012-11-09
    • 2019-04-16
    • 2013-08-08
    • 2017-09-16
    • 1970-01-01
    • 2011-12-17
    相关资源
    最近更新 更多