Check if httponly cookie exists in Javascript

这一生的挚爱 提交于 2019-11-30 03:05:30

问题


As the question says can you find out if a cookie exists within Javascript if it is a HttpOnly? I don't need to access the information inside of it, just know it has one.

A little more information on the situation is that there was originally a web server which used a cookie as an authentication token, and it was set to httponly as it was not used by the client so it added to the security.

However now there is a change needed where the client needs to know if it has the cookie (as the site can work without the user being logged in, but if they are logged in (the auth cookie would exist) the site needs to display certain things and hide others.

There are other security precautions in place on the web server so there is no harm in the scenario where the client has an incorrect auth cookie, but the site makes it look like they are logged in, as it would delete the cookie and reject the user.


回答1:


No. And see Rob's comments below.

See this, which you probably already saw - http://en.wikipedia.org/wiki/HTTP_cookie#Secure_and_HttpOnly

An HttpOnly cookie is not accessible via non-HTTP methods, such as calls via JavaScript (e.g., referencing "document.cookie")...

Edit: Removed undefined response, I wrote a script that you may not be using :)




回答2:


You can indirectly check to see if it exists by trying to set it to a value with javascript if it can't be set, then the HTTP Only Cookie must be there (or the user is blocking cookies).

function doesHttpOnlyCookieExist(cookiename) {
   var d = new Date();
   d.setTime(d.getTime() + (1000));
   var expires = "expires=" + d.toUTCString();

   document.cookie = cookiename + "=new_value;path=/;" + expires;
   if (document.cookie.indexOf(cookiename + '=') == -1) {
       return true;
    } else {
       return false;
    }
}

[UPDATE 6 Feb 2018] This doesn't work on firefox (works on Chrome & Edge, maybe others)



来源:https://stackoverflow.com/questions/9353630/check-if-httponly-cookie-exists-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!