Why do cookie values with whitespace arrive at the client side with quotes?

When you set a cookie value with one of the following values as mentioned in Cookie#setValue(),

With Version 0 cookies, values should not contain white space, brackets, parentheses, equals signs, commas, double quotes, slashes, question marks, at signs, colons, and semicolons. Empty values may not behave the same way on all browsers.

then the average container will implicitly set the cookie to version 1 (RFC 2109 spec) instead of the default version 0 (Netscape spec). The behaviour is not specified by the Servlet API, the container is free to implement it (it may for example throw some IllegalArgumentException). As far as I know, Tomcat, JBoss AS and Glassfish behave all the same with regard to implicitly changing the cookie version. For at least Tomcat and JBoss AS this is the consequence of fixes for this security issue.

A version 1 cookie look like this:

name="value with spaces";Max-Age=3600;Path=/;Version=1

while a version 0 compatible cookie look like this:

name=value%20with%20spaces;Expires=Mon, 29-Aug-2011 14:30:00 GMT;Path=/

(note that an URL-encoded value is valid for version 0)

Important note is that Microsoft Internet Explorer doesn’t support version 1 cookies. It’ll interpret the quotes being part of the whole cookie value and will treat and return that accordingly. It does not support the Max-Age attribute and it’ll ignore it altogether which causes that the cookie’s lifetime defaults to the browser session. You was apparently using IE to test the cookie handling of your webapp.

In case you wish to support browsers which doesn’t support version 1 cookies, then you need to URL-encode and URL-decode the cookie value yourself:

Cookie cookie = new Cookie(name, URLEncoder.encode(value, "UTF-8"));
// ...

and

String value = URLDecoder.decode(cookie.getValue(), "UTF-8"));
// ...

Leave a Comment