How do i get the latest cookie using js? - javascript

How can i get the latest cookie sent from a domain ?
eg :
cookies
1 - ABC
2 - ABC123
3 - ABC456
These 3 cookies has been sent from a domain, how do i find which one is the latest one?
Thanks.

From Wikipedia:
Beside the name/value pair, a cookie
may also contain an expiration date, a
path, a domain name, and whether the
cookie is intended only for encrypted
connections. RFC 2965 also specifies
that cookies must have a mandatory
version number, but this is usually
omitted.
So you can:
Check the version number, if there is one
Check the expiration date, assuming it's being set based on current time + some amount
As far as I know, that's all you can do. If you're involved in setting the cookie, you can put the information you need into one of the properties above when you set it.

Related

How to set cookies client-side taking into account Intelligent Tracking Protection?

According to this blog post on webkit.org, cookies set client-side using document.cookie are capped to a 7 day expiry.
I understand the rationale behind using httpOnly for sensitive cookies such as auth tokens, but if I need to store something for a long duration and have it available across subdomains of a site, then cookies are the only option, right?
With these new ITP restrictions, setting cookies client-side which should live for any longer duration of time is not going to work, so what's the best way to approach this? One idea was make a route which takes params and converts them into a Set-Cookie header and then make a request to that instead of using document.cookie. Is there a better way?
One attempt would be to use localStorage instead of cookies, technically they don't expire. The Problem however can be, that the user can decide to empty the localStorage.
Here's an example
//use this if you only need it for the current page and remove it after leaving the page
const exampleStorage = window.localStorage;
exampleStorage.setItem('currentUser', 'Manuel');
//use this if you need to keep it even after leaving the page
localStorage.setItem('glob_currentUser', 'Max');
//and finally this if you need to keep it only for the session
sessionStorage.setItem("session", "Morning")
If you need more Information about LocalStorage here are 2 helpful websites:
MDN Window​.local​Storage
The W3C Specification for localStorage

Overwriting HttpOnly cookie by JavaScript? [duplicate]

Say for example I had an application sending the following HTTP headers to set to cookie named "a":
Set-Cookie: a=1;Path=/;Version=1
Set-Cookie: a=2;Path=/example;Version=1
If I access /example on the server both paths are valid, so I have two cookies named "a"! Since the browser doesn't send any path information, the two cookies cannot be distinguished.
Cookie: a=2; a=1
How should this case be handled? Pick the first one? Create a list with all cookie values? Or should such a case be considered as a developer's mistake?
The answer referring to an article on SitePoint is not entirely complete. Please see RFC 6265 (to be fair, this RFC was released in 2011 after this question was posted, which supersedes previous RFC 2965 from 2000 and RFC 2109 from 1997).
Section 5.4, subsection 2 has this to say:
The user agent SHOULD sort the cookie-list in the following order:
Cookies with longer paths are listed before cookies with shorter paths.
NOTE: Not all user agents sort the cookie-list in this order, but this
order reflects common practice when this document was written, and,
historically, there have been servers that (erroneously) depended on
this order.
There is also this little gem in section 4.2.2:
... servers SHOULD NOT rely upon the serialization order. In
particular, if the Cookie header contains two cookies with the same
name (e.g., that were set with different Path or Domain attributes),
servers SHOULD NOT rely upon the order in which these cookies appear in the header.
In your example request cookie (Cookie: a=2; a=1) note that the cookie set with the path /example (a=2) has a longer path than the one with the path / (a=1) and so it is sent back to you first in line, which matches the recommendation of the spec. Thus you are more or less correct in your assumption that you could select the first value.
Unfortunately the language used in RFCs is extremely specific - the use of the words SHOULD and SHOULD NOT introduce ambiguity in RFCs. These indicate conventions that should be followed, but are not required to be conformant to the spec. While I understand the RFC for this quite well, I haven't done the research to see what real-world clients do; it's possible one or more browsers or other softwares acting as HTTP clients may not send the longest-path cookie (eg: /example) first in the Cookie: header.
If you are in a position to control the value of the cookie and you want to make your solution foolproof, you are best off either:
using a different cookie name to override in certain paths, such as:
Set-cookie: a-global=1;Path=/;Version=1
Set-cookie: a-example=2;Path=/example;Version=1
storing the path you need in the cookie value itself:
Set-cookie: a=1&path=/;Path=/;Version=1
Set-cookie: a=2&path=/example;Path=/example;Version=1
Both of these workarounds require additional logic on the server to pick the desired cookie value, by comparing the requested URL against the list of available cookies. It's not too pretty. It's unfortunate the RFC did not have the foresight to require that a longer path completely overrides a cookie with a shorter path (eg: in your example, you would receive Cookie: a=2 only).
From this article on SitePoint:
If multiple cookies of the same name match a given request URI, one is chosen by the browser.
The more specific the path, the higher the precedence. However precedence based on other attributes, including the domain, is unspecified, and may vary between browsers. This means that if you have set cookies of the same name against “.example.org” and “www.example.org”, you can’t be sure which one will be sent back.
Edit: this information from 2010 appears to be outdated, it seems browsers can now send multiple cookies in return, see answer by #Nate below for details
#user2609094 clarifies the behaviour around paths, so I thought I'd add a quick answer for the behaviour around domains (which is unspecified).
If you create cookies for a domain and subdomain ("foo.example.org" and "example.org") with the same name then the browser will send both cookies, with no indication of which one is which. Additionally, the order does not appear to be based on which domain is more specific. From testing in Google Chrome, the cookies are simply sent in the order they were created - so you can't make any assumptions about which one is which.
There is nothing wrong with having multiple values for the same name... if you want them. You might even embed additional context in the value.
If you don't, then of course different names are a solution if you want both contexts.
The alternative is to send the same cookie name with the same path (and domain) even from the more specific paths. Those set cookie instructions will overwrite the value of that cookie.
Now that you know the most important part (how they work), and that you can accomplish what you need in a few different ways, my answer to your question is: this is a developer issue.
I'm certainly aware of applications which do this extensively using multiple session ids - and seem to work consistently. However I don't know - and have no intention of finding out - if they do so because the browser returns the cookies in a consistent order depending on when they were set / which path they were set for or whether the app tries to match each one to an existing session.
I would strongly recommend that this practice be avoided.
However if you really want to know how the browsers (and apps) handle this scenario, why not build a test rig and try it out.
If you use the Java/Scala framework Play: watch out! If a request contains multiple cookies with the same name, Play will only present 1 of them to your code.
If you need to distinguish them you have to give them different key values.

Can the name-value-pair of a cookie not contain the character =?

I am dealing with a third party JavaScript code that sets a cookie through document.cookie= but without using the key=value format ; instead of doing document.cookie="mykey=myvalue" it does document.cookie="10254/1/19,20,/0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,//20".
This leads to issue on my server side code, as Chrome and Firefox send this to my server as a cookie without name and with value "10254/1/19,20,/0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,//20". Safari sends a series of cookies without values and with names "10254/1//0,//-1", "10254/1//0,1,//-1", "10254/1//0,1,2,//-1", etc.
Is it legal to set a cookie without the format key=value? I've read https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1 and seen cookie-pair = cookie-name "=" cookie-value but it is not clear for me whether = is mandatory. I think it is, just would like a confirmation.
Answering myself: cookies without = should be ignored by the user agent. From http://trac.tools.ietf.org/wg/httpstate/trac/ticket/1
Per discussion on the mailing list and at IETF77, I've removed nameless cookies from the draft. Cookies without names (either because they lack a "=" or because "=" occurs as the first character of the set-cookie-string") are now ignored by the user agent.
But in practice browsers do send cookies whose name-value-pair does not contain =. They do not have the same behavior though: for instance if I set a cookie with document.cookie("foo"), Safari will send to the server a cookie with name "foo" and a blank value, while Chrome will send a cookie with a blank name a the value "foo".

Get the users local time accurately

I am working on a project which primarily uses javascript, css, html5. I need to get the local time accurately no mater where the user is located to allow user to access a module on a particular date. Assume 1 September.
How do i get the users local time accurately?
Options:
1: Use JavaScript to get the users local time and use it.
problem: The user can manually change the date time settings of his system to change the date and access the module prematurely.
2: Use server date time to enable a module on a particular date.
problem: The server could be located anywhere eg: in U.S. and people in Australia will not be able to access the module unless the date in U.S is 1 September.
Is there any other option.
Is using client IP address a option?
well, the user's time/date info is not included in the http request header, so php will not automatically have that information. You can, as you said, use javascript to get the user's time similar to what was posted here: Determine a User's Timezone -- this is with pure javascript, if you use jquery or something similar to it, you can do it very easily.
if these are registered users however, you can allow them to set a timezone in their profile/settings, and then just use THAT setting, so even if they are traveling, they will always be set to the "home" timezone.
does that help?
First of all you should always assume user may fake any data calculated on his side. Therfore using server time is more reliable.
Using IP is an option - you can find services and databases that allow you to resolve IP to country its located in. Example: http://php.net/manual/en/book.geoip.php
Lastly - why do you want efectively differend release date for various countries? They can always use someone in other country to access module in their name.
If the user gives permission, and is using a supported browser, etc, you can get their location using navigator.geolocation.getCurrentPosition().
See developer.mozilla.org/en-US/docs/Web/API/Geolocation.getCurrentPosition for parameters and more info.
You can then use a service such as provided by geonames.org. Eg, http://api.geonames.org/timezone?lat=47.01&lng=10.2&username=demo . This returns the time at the given coords.
Update as per first comment: Of course you can never trust any data coming in from outside. But you can do things to raise levels of confidence. This wasn't meant to be a full stand-alone solution.

How do I distinguish between duplicate cookies?

I am observing, on both Firefox and IE, that if I have a cookie 'x' on the domain a.b.c.com, and also have a cookie with the same name 'x' on domain a.b.com, then when I look at the value of document.cookie on the a.b.c.com domain, it shows both cookies. I would like to see just the cookie from the a.b.c.com domain, and not the one from the other domain. (I'm assuming this occurs because one domain is the same as the other one, with an additional segment on the hostname.) Is there a way to do this?
I don't have control over the contents of the cookie, and I don't see anything obvious in those contents that distinguishes one domain from the other.
You don't have access to the domain of the cookie in Javascript.
"When [the cookie] attribute is read, all
cookies are returned as a single
string, with each cookie's name-value
pair concatenated into a list of
name-value pairs, each list item being
separated by a ';' (semicolon)."
W3C
When you read a cookie, you only have access to the name/value pairs, and cannot determine any other information about it. If you require things such as when it was set, what domains it was set for, or anything else, you have to store it inside the cookie value.
Since you cannot set the cookies, you need another method to do what you're attempting.

Categories

Resources