最近升级某个依赖库,遇到cookie解析失败的问题,网上查了查资料,在这里学习记录一下。
背景
近日有用户反馈tomcat升级后应用出现了一些问题,出现问题的这段时间内,tomcat从8.0.47升级到了8.5.43。 问题主要分为两类:
- cookie写入过程中,domain如果以
.开头则无法写入,比如.xx.com写入会报错,而写入xx.com则没问题。 - cookie读取后应用无法解析,写入cookie的值采用的是
Base64算法。
定位
经过一番搜索,发现tomcat在这两个版本中,cookie的写入和解析策略确实发生了一些变化,可见Tomcat的文档,里面有这么一段提示:
The standard implementation of CookieProcessor is org.apache.tomcat.util.http.LegacyCookieProcessor. Note that it is anticipated that this will change to org.apache.tomcat.util.http.Rfc6265CookieProcessor in a future Tomcat 8 release.
由于8.0过后就直接到了8.5,
- 从
8.5开始就默认使用了org.apache.tomcat.util.http.Rfc6265CookieProcessor - 而之前的版本中一直使用的是
org.apache.tomcat.util.http.LegacyCookieProcessor,
下面就来看看这两种策略到底有哪些不同.


LegacyCookieProcessor
org.apache.tomcat.util.http.LegacyCookieProcessor主要是实现了标准RFC6265, RFC2109 和 RFC2616.
写入cookie
写入cookie的逻辑都在generateHeader方法中. 这个方法逻辑大概是:
- 直接拼接
cookie.getName()然后拼接=. - 校验
cookie.getValue()以确定是否需要为value加上引号.
private void maybeQuote(StringBuffer buf, String value, int version) {
if (value == null || value.length() == 0) {
buf.append("\"\"");
} else if (alreadyQuoted(value)) {
buf.append('"');
escapeDoubleQuotes(buf, value,1,value.length()-1);
buf.append('"');
} else if (needsQuotes(value, version)) {
buf.append('"');
escapeDoubleQuotes(buf, value,0,value.length());
buf.append('"');
} else {
buf.append(value);
}
}
private boolean needsQuotes(String value, int version) {
...
for (; i < len; i++) {
char c = value.charAt(i);
if ((c < 0x20 && c != '\t') || c >= 0x7f) {
throw new IllegalArgumentException(
"Control character in cookie value or attribute.");
}
if (version == 0 && !allowedWithoutQuotes.get(c) ||
version == 1 && isHttpSeparator(c)) {
return tru

本文讲述了在升级Tomcat依赖库后遇到的cookie解析失败问题,主要聚焦于LegacyCookieProcessor和Rfc6265CookieProcessor的区别,以及如何通过配置解决跨版本兼容性问题。

192

被折叠的 条评论
为什么被折叠?



