如何使用 javascript 设置 cookie 的 HttpOnly 标志?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4999360/
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
How do I set the HttpOnly flag of a cookie with javascript?
提问by user617136
I'm trying to create a cookie, with the HttpOnly flag enabled.
我正在尝试创建一个 cookie,并启用了 HttpOnly 标志。
While there seems to be a plethora of resources about how to do it in Java and .Net, I need to do it in javascript.
虽然似乎有大量关于如何在 Java 和 .Net 中执行此操作的资源,但我需要在 javascript 中执行此操作。
Here is my (currently failing) function
这是我的(目前失败的)功能
createCookie = function(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; domain=my.domain.com; path=/; HttpOnly;";
Thanks -
谢谢 -
回答by Yevhen Pavliuk
You cannot access an HttpOnly cookie in JavaScript.
您无法在 JavaScript 中访问 HttpOnly cookie。
The following quotation is borrowed from the Wikipedia material:
The HttpOnly cookie is supported by most modern browsers. On a supported browser, an HttpOnly session cookie will be used only when transmitting HTTP (or HTTPS) requests, thus restricting access from other, non-HTTP APIs (such as JavaScript).
大多数现代浏览器都支持 HttpOnly cookie。在受支持的浏览器上,仅在传输 HTTP(或 HTTPS)请求时才会使用 HttpOnly 会话 cookie,从而限制来自其他非 HTTP API(例如 JavaScript)的访问。
In other words, HttpOnly cookies are made to be used only on the server side.
换句话说,HttpOnly cookie 只在服务器端使用。
I wrote an example in PHP:
我用PHP写了一个例子:
<?php
$name = 'foo';
$value = 'bar';
$expirationTime = 0; // Session cookie.
$path = '/';
$domain = 'localhost';
$isSecure = false;
$isHttpOnly = false;
setcookie($name, $value, $expirationTime, $path, $domain, $isSecure, $isHttpOnly);
?>
<script>
alert(document.cookie);
</script>
It alerts foo=bar
.
它发出警报foo=bar
。
Remove the cookie, change $isHttpOnly
to true
, reload the page, and you'll see an empty alert. But at the same time the browser stores the cookie to send it during a request to the server.
删除 cookie,更改$isHttpOnly
为true
,重新加载页面,您将看到一个空警报。但与此同时,浏览器会存储 cookie,以便在向服务器发出请求期间将其发送。