如何使用 javascript 设置 cookie 的 HttpOnly 标志?

发布于 2024-10-17 13:20:45 字数 468 浏览 1 评论 0原文

我正在尝试创建一个 cookie,并启用 HttpOnly 标志。

虽然似乎有大量关于如何在 Java 和 .Net 中执行此操作的资源,但我需要在 javascript 中执行此操作。

这是我的(目前失败的)功能

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;";

谢谢 -

I'm trying to create a cookie, with the HttpOnly flag enabled.

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.

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 -

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不必在意 2024-10-24 13:20:45

您无法在 JavaScript 中访问 HttpOnly cookie。

以下引文借用自维基百科资料

大多数现代浏览器都支持 HttpOnly cookie。在受支持的浏览器上,仅在传输 HTTP(或 HTTPS)请求时才会使用 HttpOnly 会话 cookie,从而限制来自其他非 HTTP API(例如 JavaScript)的访问

换句话说,HttpOnly cookie 只在服务器端使用。

我用 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>

它会提醒 foo=bar

删除 cookie,将 $isHttpOnly 更改为 true,重新加载页面,您将看到一个空警报。但同时浏览器会存储 cookie,以便在向服务器发出请求时将其发送。

You cannot access an HttpOnly cookie in JavaScript.

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).

In other words, HttpOnly cookies are made to be used only on the server side.

I wrote an example in 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.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文