Check if httponly cookie exists in Javascript

前端 未结 4 1791

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.

相关标签:
4条回答
  • 2020-12-16 15:04

    I had the same problem. I solved it with the server setting another cookie, not httponly, every time it refreshed the httponly session cookie, with the same max-age and no sensitive data. Now, if one of them is present, the same goes for the other, and the client can know if the httponly counterpart is there.

    0 讨论(0)
  • 2020-12-16 15:05

    Whenever you need to check whether the cookie exists or not, you can send a request to the server that requires authentication & check the response. If its something like 401 Unauthorized or 403 Forbidden, then the cookie probably doesn't exist & you can prompt the user for login.

    On the other hand, if the cookie exists, it'll be automatically sent by the browser resulting in a 200 OK response.

    0 讨论(0)
  • 2020-12-16 15:11

    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;
      }
    }
    
    0 讨论(0)
  • 2020-12-16 15:18

    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 :)

    0 讨论(0)
提交回复
热议问题