通过 Javascript 将 cookie 设置为 HttpOnly

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14691654/
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-08-24 17:37:43  来源:igfitidea点击:

Set a cookie to HttpOnly via Javascript

javascripthttpcookies

提问by BalusC

I have a cookie that is NOT HttpOnlyCan I set this cookie to HttpOnlyvia JavaScript?

我有一个不是的 cookieHttpOnly我可以HttpOnly通过 JavaScript设置这个 cookie吗?

回答by BalusC

An HttpOnlycookie means that it's notavailable to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnlyattribute of the cookie, as that would otherwise defeat the meaning of HttpOnly.

一个HttpOnlycookie的手段,它是提供给脚本语言如JavaScript。所以在 JavaScript 中,绝对没有 API 可用于获取/设置HttpOnlycookie的属性,否则会破坏HttpOnly.

Just set it as such on the server side using whatever server side language the server side is using. If JavaScript is absolutely necessary for this, you could consider to just let it send some (ajax) request with e.g. some specific request parameter which triggers the server side language to create an HttpOnly cookie. But, that would still make it easy for hackers to change the HttpOnlyby just XSS and still have access to the cookie via JS and thus make the HttpOnlyon your cookie completely useless.

只需使用服务器端使用的任何服务器端语言在服务器端设置它。如果 JavaScript 是绝对必要的,你可以考虑让它发送一些(ajax)请求,例如一些特定的请求参数,触发服务器端语言创建一个 HttpOnly cookie。但是,这仍然会让黑客很容易HttpOnly通过 XSS来改变它,并且仍然可以通过 JS 访问 cookie,从而使HttpOnly你的 cookie 完全无用。