简体   繁体   English

检查Cookie是否设置了安全标记并仅使用JavaScript更新

[英]Check if Cookie has Secure Flag set and update using JavaScript ONLY

My issue is we set some cookies, using JS, with a 1 year expiration and that particular cookie didn't have the secure flag set. 我的问题是,我们使用JS设置了一些cookie,这些cookie的有效期为1年,并且该特定cookie没有设置安全标志。 We now want to update the cookies to have the secure flag set. 现在,我们要更新cookie以设置安全标志。 The code that creates the cookies now has the "secure" attribute and all new cookies have the "secure" flag. 创建cookie的代码现在具有“安全”属性,所有新cookie均具有“安全”标志。 The issue is how do I update existing cookies? 问题是如何更新现有的Cookie? I'm assuming I have to destroy the cookie and then recreate it with the secure flag set? 我假设我必须销毁cookie,然后使用安全标志集重新创建它? I don't know if there is any other way to do this? 我不知道还有其他方法吗? Also is there a way using JavaScript to detect if the cookie does have the flag set before deleting it? 还有一种使用JavaScript的方法来删除Cookie之前是否检测到cookie是否设置了标志?

Thanks! 谢谢!

You can't check cookies flags with pure JavaScript. 您不能使用纯JavaScript检查cookie标志。 If you want to add flag, just create a new one cookie and browser will overwrite old. 如果要添加标志,只需创建一个新的cookie,浏览器将覆盖旧的cookie。

Example: 例:

Type in console: 在控制台中输入:

const year = 60*60*24*365;
document.cookie = 'mytestcookie=1;max-age='+year;

And look into cookies tab in your browser developer tools. 并查看浏览器开发人员工具中的Cookie选项卡。 You will see it's insecure. 您将看到它是不安全的。 Now, type: 现在,键入:

document.cookie = 'mytestcookie=2;max-age='+year+';secure';

Look again. 再看一遍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM