开发者

How do I set the HttpOnly flag of a cookie with javascript?

开发者 https://www.devze.com 2023-02-10 06:36 出处:网络
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.

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 va开发者_运维知识库r expires = "";
document.cookie = name+"="+value+expires+"; domain=my.domain.com; path=/; HttpOnly;";

Thanks -


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号