I have a cookie that is NOT HttpOnly Can I set this cookie to HttpOnly via JavaScript?
-
1How would it be possible to set a cookie by JavaScript which JavaScript itself isn't supposed to be able to manipulate? Just set it in the server side.BalusC– BalusC2013-02-04 17:05:37 +00:00Commented Feb 4, 2013 at 17:05
-
2The Cookie is NOT HttpOnly and i want to set it to HttpOnly via Javascript.user887983– user8879832013-02-04 17:06:35 +00:00Commented Feb 4, 2013 at 17:06
-
10I think you miss the point of HttpOnly.BalusC– BalusC2013-02-04 17:06:48 +00:00Commented Feb 4, 2013 at 17:06
-
6Great question. There really isn't any downside to setting an HttpOnly cookie from the client as far as security goes. So you'd think that it would be allowed. But of course it isn't.PHP Guru– PHP Guru2020-09-30 23:49:19 +00:00Commented Sep 30, 2020 at 23:49
1 Answer
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.
Just set it as such on the server side using whatever server side language the server side is using. If JavaScript is absolutely necessary for this, you could consider to just let it send some (ajax) request with e.g. some specific request parameter which triggers the server side language to create an HttpOnly cookie. But, that would still make it easy for hackers to change the HttpOnly by just XSS and still have access to the cookie via JS and thus make the HttpOnly on your cookie completely useless.