未使用 javascript 设置 Samesite cookie 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50361460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:03:43  来源:igfitidea点击:

Samesite cookie attribute not being set using javascript

javascriptcookiessamesite

提问by Satya

I am trying to set SameSite attribute using javascript on my site . The code is

我正在尝试在我的网站上使用 javascript 设置 SameSite 属性。代码是

<script type="text/javascript">

    document.cookie = "AC-C=ac-c;expires=Fri, 31 Dec 9999 23:59:59 GMT;path=/;HttpOnly;SameSite=Lax";
  </script>

The cookie is being set but the SameSite attribute is not being set. Any idea where am I missing?

正在设置 cookie,但未设置 SameSite 属性。知道我在哪里失踪了吗?

Thanks

谢谢

回答by iiic

Your problem is not with SameSite, but with HttpOnly. HttpOnlyand SameSiteare 2 independent things, if you remove HttpOnlyit will be working…?and cookie will be set with SameSite.

您的问题不在于SameSite,而在于HttpOnlyHttpOnly并且SameSite是 2 个独立的东西,如果您将HttpOnly其删除,它将起作用……?并且 cookie 将设置为SameSite.

<script>
    document.cookie = "AC-C=ac-c;expires=Fri, 31 Dec 9999 23:59:59 GMT;path=/;SameSite=Lax";
    alert( document.cookie );
</script>

回答by mikep

You can not set HttpOnly flag via JavaScript API document.cookie. Flag HttpOnlycan be set only via cookie header in server response. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CookiesCookies created via JavaScript cannot include the HttpOnly flag.

您不能通过 JavaScript API document.cookie 设置 HttpOnly 标志。标志HttpOnly只能通过服务器响应中的 cookie 标头设置。请参阅https://developer.mozilla.org/en-US/docs/Web/HTTP/CookiesCookies created via JavaScript cannot include the HttpOnly flag.

You wrote The cookie is being set but the SameSite attribute is not being setbut I think it is not truth. Cookie set via JS with attribute HttpOnly is rejected at all or maybe some browser set it but ignore HttpOnly flag - so finally your cookie is not HTTP only.

你写了,The cookie is being set but the SameSite attribute is not being set但我认为这不是事实。通过带有 HttpOnly 属性的 JS 设置的 Cookie 完全被拒绝,或者某些浏览器设置了它但忽略了 HttpOnly 标志 - 所以最后你的 cookie 不仅仅是 HTTP。