在tomcat8.0升级到8.5时会发生这样的问题

java.lang.IllegalArgumentException: An invalid domain [.tencent.xxx.com] was specified for this cookie
        at org.apache.tomcat.util.http.Rfc6265CookieProcessor.validateDomain(Rfc6265CookieProcessor.java:203)
        at org.apache.tomcat.util.http.Rfc6265CookieProcessor.generateHeader(Rfc6265CookieProcessor.java:145)
        at org.apache.catalina.connector.Response.generateCookieString(Response.java:1019)
        at org.apache.catalina.connector.Response.addCookie(Response.java:967)
        at org.apache.catalina.connector.ResponseFacade.addCookie(ResponseFacade.java:386)
        ......

在某个filter中设置顶层域名cookie,然后报了这个错,应该是域名验证的时候错误了,这里的tomcat版本为8.5.16,jdk版本1.8.0_191
去看tomcat的源码,对应189~218行

private void validateDomain(String domain) {
        int i = 0;
        int prev = -1;
        int cur = -1;
        char[] chars = domain.toCharArray();
        while (i < chars.length) {
            prev = cur;
            cur = chars[i];
            if (!domainValid.get(cur)) {
                throw new IllegalArgumentException(sm.getString(
                        "rfc6265CookieProcessor.invalidDomain", domain));
            }
            // labels must start with a letter or number
            if ((prev == '.' || prev == -1) && (cur == '.' || cur == '-')) {
                throw new IllegalArgumentException(sm.getString(
                        "rfc6265CookieProcessor.invalidDomain", domain));
            }
            // labels must end with a letter or number
            if (prev == '-' && cur == '.') {
                throw new IllegalArgumentException(sm.getString(
                        "rfc6265CookieProcessor.invalidDomain", domain));
            }
            i++;
        }
        // domain must end with a label
        if (cur == '.' || cur == '-') {
            throw new IllegalArgumentException(sm.getString(
                    "rfc6265CookieProcessor.invalidDomain", domain));
        }
    }

203行抛出的异常,这个方法就是验证domain是否正确的,两个指针一个指向当前的char,一个指向上一个char,初始-1,那么这个当这个域名以’.’或者’-’的开头的时候就会抛出这个异常

根据这个原理,将前面的点号去掉,测试就OK了

原因分析:

跟踪addCookie方法

发现这个generateHeader方法中有两个实现,经搜索得知,tomcat8.5版本默认使用的是rfc6265实现的,而tomcat8.0版本是LegacyCookieProcessor

而在rfc6265中看到了域属性这段话,域属性不要以dot开头
所以,类似的cookie.setDomain(".test.com");在rfc6265标准中应该改为cookie.setDomain(“test.com”),即开头不要加点号

规则:

  1. 必须是1-9、a-z、A-Z、. 、- (注意是-不是_)这几个字符组成
  2. 必须是数字或字母开头 (所以以前的cookie的设置为.XX.com 的机制要改为 XX.com 即可)
  3. 必须是数字或字母结尾

在生产环境中,我们都不想去改代码,这个时候也有解决的方法
修改${tomcat_home}\conf\context.xml文件

<?xml version="1.0" encoding="UTF-8”?>
<!-- The contents of this file will be loaded for each web application -->
<Context>
<!-- Default set of monitored resources. If one of these changes, the    -->
<!-- web application will be reloaded.                                   -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!-- <Manager pathname="" /> -->
<!-- 添加代码 -->
<CookieProcessor className="org.apache.tomcat.util.http.LegacyCookieProcessor"/>
</Context>

将cookie处理的手工设置为LegacyCookieProcessor即可

如果是Spring boot中也是类似的道理
参考文档:https://docs.spring.io/spring-boot/docs/2.0.3.RELEASE/reference/htmlsingle/#howto-use-tomcat-legacycookieprocessor

@Bean
public WebServerFactoryCustomizer<TomcatServletWebServerFactory> cookieProcessorCustomizer() {
	return (factory) -> factory.addContextCustomizers(
			(context) -> context.setCookieProcessor(new LegacyCookieProcessor()));
}

文档中写的配置这样一个bean就行了。

我这边项目中的解决方案

SpringBoot 1.x:

@Bean
      public EmbeddedServletContainerCustomizer cookieProcessorCustomizer() {
          return new EmbeddedServletContainerCustomizer() {

              @Override
              public void customize(ConfigurableEmbeddedServletContainer container) {
                  if (container instanceof TomcatEmbeddedServletContainerFactory) {
                      ((TomcatEmbeddedServletContainerFactory) container)
                              .addContextCustomizers(new TomcatContextCustomizer() {

                          @Override
                          public void customize(Context context) {
                              LegacyCookieProcessor legacyCookieProcessor = new LegacyCookieProcessor();
                              legacyCookieProcessor.setAllowEqualsInvalue(true);
                              context.setCookieProcessor(new LegacyCookieProcessor());
                          }

                      });
                  }
              }

          };
      }

或者:

@Bean
    public EmbeddedServletContainerCustomizer customizer() {
        return container -> {
            if (container instanceof TomcatEmbeddedServletContainerFactory) {
                TomcatEmbeddedServletContainerFactory tomcat = (TomcatEmbeddedServletContainerFactory) container;
                tomcat.addContextCustomizers(context -> context.setCookieProcessor(new LegacyCookieProcessor()));
            }
        };
    }

SpringBoot 2.x:

@Bean
    public WebServerFactoryCustomizer<TomcatServletWebServerFactory> cookieProcessorCustomizer() {
        LegacyCookieProcessor legacyCookieProcessor = new LegacyCookieProcessor();
        legacyCookieProcessor.setAllowEqualsInValue(true);
        return (factory) -> factory.addContextCustomizers(
        (context) -> context.setCookieProcessor(legacyCookieProcessor));

    }
Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐