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.
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;
return document.cookie.indexOf(cookiename + '=') == -1;
}
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.
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 :)
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.
Related
I have a cookie set on a response from a page (via http) and it is shows as Session Cookie only , and when i try to do
document.cookie = key + '=' + value + ';
expires=' + date.toGMTString() + ';
path=/';
it does not alter the cookie. I tried without expires but it created another one with the same name and it will be Host-Only and Session Only .
I really dont know how to alter this cookie. tried everything
I am sure this cookie has HttpOnly falg on it. So you can't modify a cookie with HttpOnly flag set on it. You can't even access it using any client side script.
If the HttpOnly flag (optional) is included in the HTTP response header, the cookie cannot be accessed through client side script (again if the browser supports this flag). As a result, even if a cross-site scripting (XSS) flaw exists, and a user accidentally accesses a link that exploits this flaw, the browser (primarily Internet Explorer) will not reveal the cookie to a third party.
Read more here
I can't access any cookie from JavaScript. I need to read some value and send them via JSON for my custom checks.
I've tried to access cookies from JS, like it was described at:
http://www.w3schools.com/js/js_cookies.asp
Get cookie by name
As you can see at the code, it's seen as clear as a crystal the next:
var c_value = document.cookie;
When I'm trying to access the document.cookie value from the Chrome's web-debugger, I see only the empty string at the Watch expressions:
So I can't read cookies value, which I need.
I've checked the cookie name, which I'm sending to get an associated value IS correct.
Also, I'm using the W3Schools source code for getting cookies, if you're interested (but from the 2nd link, the technique is similar).
How can I fix my issue?
You are most likely dealing with httponly cookies. httponly is a flag you can set on cookies meaning they can not be accessed by JavaScript. This is to prevent malicious scripts stealing cookies with sensitive data or even entire sessions.
So you either have to disable the httponly flag or you need to find another way to get the data to your javascript.
By looking at your code it should be easy to disable the http only flag:
Response.AddHeader("Set-Cookie", "CookieName=CookieValue; path=/;");
Response.SetCookie(new HttpCookie("session-id") { Value = Guid.NewGuid().ToString(), HttpOnly = false });
Response.SetCookie(new HttpCookie("user-name") { Value = data.Login, HttpOnly = false });
Now you should be able to access the cookie information from JavaScript. However I don't know exactly what kind of data you are trying to get so maybe you can go for another approach instead and for example render some data attribute on the page with the information you need instead of trying to read the cookie:
<div id="example" data-info="whatever data you are trying to retrieve"></div>
console.log(document.getElementById('example').getAttribute('data-info'));
keep an eye also to the cookie's Path attribute, as the cookie is only visible to subdirectories under Path. I had your issue and I solved setting Path "/"
I would say http only is your first culprit but this can also occur by not setting the scope of your cookie.
If the site has been redirected from another domain, you will need to look into setting the scope of the cookie. Domain and Path defines the scope of the cookie, which URLs the cookie should be sent to. Depending on this, you might not see the cookie in your response.
I ran across this issue when setting a cookie on a successful SAML SSO login and couldn't retrieve the cookie from the Document because it was never send as part of the request.
I had the same problem several times. And every time, it was for a different reason.
Different reasons:
problem of httpOnly field. It was set to false and I was trying to access it from the console. Setting it to true or accessing it from the source code did the trick.
problem of secure field. It was true and I was using only http.
problem of Expires / Max-Age. The cookie was outdated and it was not visible in document.cookie.
If your cookie is set as Set-Cookie or Set-Cookie2 it's not part of the response headers collection: http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders%28%29-method
Returns all headers from the response, with the exception of those whose field name is Set-Cookie or Set-Cookie2.
If you are using some secure authentication then that case you could not access cookies directly because of secure. you have to change some response attribute in server side using below code .
Response.AddHeader("Set-Cookie", "CookieName=CookieValue; path=/;");
Response.SetCookie(new HttpCookie("session-id") { Value = Guid.NewGuid().ToString(), HttpOnly = false });
Response.SetCookie(new HttpCookie("user-name") { Value = data.Login, HttpOnly = false });
But you should not because it may change secure to un-secure, so you have to find out solution that be done in server side to delete cookies and allow to you do some operations.
Its possible to do changes in server side.
Javascript not reading cookies set by Laravel in the same domain and returning undefined.
It's only reading the XSRF-Token but not any other cookies whether be it encrypted or unencrypted.
The URL is: http://localhost:8000/myaccount
and here is the cookie screenshot
I'm using JS Cookie library .. It's not reading either using document.cookie or Cookies.get('user_id') only the XSRF-TOKEN is reading.
Cookie user-id has http-only flag set to true.
It is not therefore accessible by javascript.
Try and set http-only flag to false.
edit: check this other SO answer it might get you started
The cookie is HttpOnly, therefore cannot be read by Javascript. You have to set the cookie as $httpOnly = false
See the last parameter of CookieJar::make method - which is mirrored in facade Cookie::make method.
I am setting a cookie in Node-Express JS with JWT token as part of cookie with following code.
var token = jwt.sign(parsed.data, "token_secret", {expiresIn: "43200m"});
res.setHeader('Set-Cookie', 'token='+token+';expires='+new Date(new Date().getTime()+9940900000).toUTCString());
On closing or quitting the browser the cookie is getting deleted.
What is the best way to retain the cookie? Is it storing the token in localStorage in browser and attaching it to header for every http request? Or is there any other way of setting cookie, so that cookie is not deleted after browser is closed.
Maybe this
document.cookie = cName + "=" + cValue + "; expires=" + expDate + ";path=/";
There are different types of cookies available, to know Refer HTTP Cookie
One of which are session cookie, here is definition from wiki,
A session cookie, also known as an in-memory cookie or transient cookie, exists only in temporary memory while the user navigates the website.[13] Web browsers normally delete session cookies when the user closes the browser.[14] Unlike other cookies, session cookies do not have an expiration date assigned to them, which is how the browser knows to treat them as session cookies.
So if you don't want your cookie to expire after browser close then use Persistent Cookie.
To do so refer,
Persistent cookies in node js express
Hope that helps!
I try to set a cookie in browser ( here chrome ver.41.xxx ) using debugger's console:
> document.cookie = 'cookie1=hans; expires=Fri, 03 May 2020 11:00:00 GMT;'
Then, I inspect the .cookie property:
> document.cookie
> "cookie1=Hans"
Surprisingly, no expires section! Fiddler also reports the same when I refresh the page:
These are enough for me to believe that expires property is not set.
But, I get more surprised when I see the cookie expires using EditThisCookie extension
I tried to set the cookie using JavaScript in my code and exactly the same result!
Question: How can I make sure that the expires property of the cookie is set?
When reading from cookies, you will only be given the value of cookies which are valid for the current host, path, security setup, and time. Short of using a special browser add-on or browsing the file system (neither of which you can do from your own code), there is no way to get this info about a cookie. If it's there, it's not expired. That's just the way the cookie "API" was written.
In response to "How can I make sure that the expires property of the cookie is set?" - if you pass it, it's set. Using a cookie library to improve upon the browser's API can, however, help you get everything set with less fussy string manipulation.