Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double quotes and trailing equal sign missing from cookies values in ServletExec

I have a servlet app which stores cookies as base64-encoded strings. On a server where the app is running on ServletExec, the cookies' values are not wrapped in quotes. Additionally, if the value ends with a '=' character, that character is removed. The missing quotes and trailing '=' prevent the cookies' values from being parsed properly. In 2 other servers where this app is running on ServletExec and Tomcat where this app is working, the cookies are wrapped in double quotes and the trailing '=' sign is not removed.

As seen in a browser's developer tool:

Bad - cookiename:dGVzdHN0cmluZzE

Expected - cookiename:"dGVzdHN0cmluZzE="

Any idea what's stripping out the quotes and the trailing '=' sign? TIA!

like image 981
Zoomzoom Avatar asked Sep 17 '25 18:09

Zoomzoom


1 Answers

By default, the servlet Cookie class follows the Version 0 cookie spec. Here's a cite from the javadoc:

This class supports both the Version 0 (by Netscape) and Version 1 (by RFC 2109) cookie specifications. By default, cookies are created using Version 0 to ensure the best interoperability.

Version 0 cookie values are restrictive in allowed characters. It only allows URL-safe characters. This covers among others the alphanumeric characters (a-z, A-Z and 0-9) and only a few lexical characters, including -, _, ., ~ and %. All other characters are invalid in version 0 cookies, including " and =. If the server doesn't already do it, the browser will swallow the invalid characters.

Your best bet is to URL-encode those characters. This way every character which is not allowed in URLs will be percent-encoded in this form %xx which is valid as cookie value.

So, when creating the cookie do:

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

And when reading the cookie, do:

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

An alternative is to switch to Version 1 cookies via Cookie#setVersion(), but this isn't supported in IE<=11.

like image 187
BalusC Avatar answered Sep 21 '25 14:09

BalusC