Hi I am working with JsCookies it is working good but I am facing a problem
Whenever I store a short string in the cookies, it is working fine but the drawback is i am not able to store long strings in cookies
for example
This is working fine = Cookies.set('Coo', 'string', { expires: 1 })
But facing problem when ever i am trying to store stringified JSON data(large string)
Cookies.set('foo', JSON.stringify(result))
Please help
Cookies should not be used to store large amounts of data. They should be used for stuff like user authorization and configuration options (which, all together, don't add up to much of a payload). Use cookies when the data is relevant to both the client on the server on every request.
Large payloads in cookies should not be sent with every request; it'd be bandwidth-intensive and unnecessary. Instead, either:
If the server doesn't need the information, and you're just using it for client-side storage, use Local Storage instead
If the server does need the information, send the data to the server once (or, at least, send it to the server in a separate request, but not in the cookies) - such as through XHR.
If the server will have the information and the client needs it, send the data to the client some other way, instead of bundling it inside a cookie. For example, you could send the data by embedding it in the HTML response sent to the client, or by having the client make a network request to the server, and have the server respond with the data as JSON.
You can't store more than 4k bytes in cookies but there is an alternative for this
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
In local storage, you can store up to 5MB of data so you can go with this, but the problem is if you want to set expiration you can't do it in a simple way, you need to make functions for that. like this
Max cookie size is 4K bytes. You may not store more than that. Read more about cookie limits here: http://browsercookielimits.iain.guru/
If I run a test on my Chrome browser, here is what it says:
10:41:28.954: Guessing Max Cookie Count Per Domain: 180
10:41:28.954: Guessing Max Cookie Size Per Cookie: 4096 bytes
Use this function :
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
But there are limits to how large a cookie can be(4,096 bytes).
But you can have multiple cookies but in that too there are limits:
Chrome 9 allowed 180 cookies per domain
Firefox 3.6.3 allowed 50 cookies per domain
Internet Explorer 8 allowed 50 cookies per domain
Opera 10 and 9 allowed 30 cookies per domain
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.
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!
For one of my projects I had the following paths available in a web application:
/one
/one/two
/one/two/three
Each of the different paths are variable and used cookies as part of their variability, I had created the following cookies:
one=1; Max-Age=9600; Domain=.test.test.com; Path=/one; Expires=Wed, 30 Jul 2014 20:26:09 GMT
two=2; Max-Age=9600; Domain=.test.test.com; Path=/one/two; Expires=Wed, 30 Jul 2014 20:26:09 GMT
three=3; Max-Age=9600; Domain=.test.test.com; Path=/one/two/three; Expires=Wed, 30 Jul 2014 20:26:09 GMT
When accessing the URL (I was running my test on http://test.test.com setup in my hosts file) at the following locations I received the following results:
Visit http://test.test.com/one the correct cookie (one=1) was sent to the server, but document.cookie was empty.
Visit http://test.test.com/one/ the correct cookie (one=1) was sent to the server and document.cookie also had the correct cookie (one=1).
Visit http://test.test.com/one/two the correct cookies (one=1 and two=2) were sent to the server, but document.cookie only contained the first cookie (one=1).
Visit http://test.test.com/one/two/ the correct cookies (one=1 and two=2) were sent to the server and document.cookie also had the correct cookies (one=1 and two=2).
Visit http://test.test.com/one/two/three the correct cookies (one=1, two=2, and three=3) were sent to the server, but document.cookie only contained the first two cookies (one=1, two=2).
Visit http://test.test.com/one/two/three/ the correct cookies (one=1, two=2, and three=3) were sent to the server and document.cookie also had the correct cookies (one=1, two=2, and three=3).
This utterly confounded me, and through a bunch of testing I was only able to find Internet Explorer being impacted by this issue, please see the answer for additional details.
Due to the constraints of my project I needed to have the ability to keep cookie names the same at each of these paths and also vary them by path, so I wasn't able to come up with any solution for my situation where I could use cookies without requiring a trailing slash at the end (which due to my constraints I cannot do).
If you are running into a similar issue there's a couple things that I can think of doing:
If the name of your cookies can vary, you could use different names for each of the paths and keep the path either at the root (path=/)
If the name of your cookies cannot vary but it doesn't matter if they go up a level in the path you could do that (in my case the cookie three=3 could be placed up one directory at path=/one/two if my constraints didn't prohibit me from doing that.
If your constraints don't prohibit you from requiring trailing slashes you could simply have your webserver enforce trailing slashes and redirect to a path with them when they aren't present.
If you run into the same issue with similar constraints to mine you could just move to another storage device instead of cookies. There's other modern pieces such as localStorage and sessionStorage which would allow you to store your data in a more structured way so that you can handle the logic. Note: This only works when you don't need the data from the cookie server side.
In the end what I ended up doing was moving the cookie that I didn't need server side (three=3) to use a convention instead of configuration via cookie within the project and kept the other ones as is since the other two cookies (one=1 and two=2) are only used when visiting the path http://test.test.com/one/two/three and so they are still available through document.cookie in Internet Explorer.
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.