JavaScript复制Cookie [英] JavaScript Duplicate Cookies

查看:134
本文介绍了JavaScript复制Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Hapi框架用于Node.js应用程序,并且Hapi框架附带了自己的Cookie管理工具,该工具用于身份验证.

I'm using the Hapi framework for a Node.js application, and the Hapi framework comes with its own Cookie management tools, which i'm using for authentication.

然后,框架设置一个名为session的cookie,其json值编码为base64.域设置为example.com(不是.example.com)

The framework then sets a cookie named session, with a json value encoded to base64. The domain is set to example.com (not .example.com)

现在,问题出在我尝试通过执行以下操作来编辑此Cookie客户端

Now, the problem lies when i attempt to edit this cookie client-side, by doing the following

document.cookie = 'session=' + btoa(JSON.stringify(_decoded)) + "; path=/; domain=example.com";

这实际上设置了域".example.com"的重复Cookie

This actually sets a duplicate cookie with the domain '.example.com'

我还没有要求Javascript加上点号,而且我似乎也无法摆脱它.

I haven't asked Javascript to prepend the dot, and i cant seem to get rid of it.

我假设是由于这个点而导致cookie被复制.如何设置没有自动加点的域名?

I'm assuming that it is because of this dot, that the cookie is being duplicated. How do i set the domain without it automatically prepending a dot?

编辑

我已经放弃尝试删除前导点,而是尝试删除旧的cookie,然后创建一个新的cookie.但是我仍然会得到重复的Cookie!

I've given up on trying to remove the leading dot, and instead am trying to delete the old cookie and then create a new one. However i still end up with duplicate cookies!

  1. 导航到/login并输入登录详细信息
  2. 已重定向到服务器设置的/account和cookie(没有Leading Dot)
  3. 执行Java脚本以删除并重新创建cookie
  4. 现在有1个cookie,并且在域之前有一个前导点

上面的行为是好的,但是下面的情况也会发生,这是不好的

The above behaviour is good, however the following also happens, which is bad

  1. 导航到/login并输入登录详细信息
  2. 已重定向到服务器设置的/account和cookie(没有Leading Dot)
  3. 导航到/example
  4. 执行Java脚本以删除并重新创建cookie
  5. 现在存在2个cookie,一个带有前导点(由JS创建),另一个不带前导点(由服务器创建)

我正在使用的代码是

API.Session = {
    Encoded : function () { return document.cookie.replace(/(?:(?:^|.*;\s*)session\s*\=\s*([^;]*).*$)|^.*$/, "$1")},
    Decoded : function () { return JSON.parse(atob(this.Encoded()))},
    Update : function (_decoded) { 
        document.cookie = 'session=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
        document.cookie = 'session=' + btoa(JSON.stringify(_decoded)) + "; path=/; domain=example.com;";      
    }
}

API.Helpers.ShowAdvancedOptions = function () {
    var s = API.Session.Decoded()
    s.ShowAdvancedOptions = true
    API.Session.Update(s)
}

推荐答案

对于遇到类似问题的任何人,最终都可以通过完全删除domain属性来解决.请参阅其他相关问题

For anyone with a similar issue, this was eventually solved by dropping the domain property altogether. See other related question

这篇关于JavaScript复制Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆