Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 -

like image 252
user617136 Avatar asked Feb 15 '11 02:02

user617136


People also ask

Can we set HttpOnly cookie in JavaScript?

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 .

How do I set my cookie to 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.

Can I set HttpOnly cookie from browser?

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.


1 Answers

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.

like image 107
Yevhen Pavliuk Avatar answered Sep 21 '22 20:09

Yevhen Pavliuk