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 -
An HttpOnly cookie means that it's not available to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnly attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly .
Set HttpOnly cookie in PHPini_set("session. cookie_httponly", True); This is the most common way to set cookies in PHP, empty variables will hold their default value.
If your browser supports HttpOnly, and you enable it for a cookie, a client-side script should NOT be able to read OR write to that cookie, but the browser can still send its value to the server. However, some browsers only prevent client side read access, but do not prevent write access.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With