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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With