If the value is obtained from an untrusted source, can I use the API to safely set the value without additional preprocessing?
No, you canβt. The API will not take care of this for you. Otherwise, this would be explicitly stated in Javadoc. The API may not know in advance if you are using version 0 ( Netscape ) or version 1 ( RFC2965 ).
It would be best to just URL-encode the cookie name / value in advance so you can make sure that you end up with a secure cookie name / value.
String safeCookieName = URLEncoder.encode(name, "UTF-8"); String safeCookieValue = URLEncoder.encode(value, "UTF-8"); response.addCookie(new Cookie(safeCookieName, safeCookieValue));
Alternatively, you can also use regex to pre-remove all illegal characters. Only alphabetic characters, numbers, hyphens, underscores, periods, tildes, and possibly a few more are allowed (browser dependent!). All others must be deleted.
Balusc
source share