同事遇到的问题:
An invalid domain was specified for this cookie:
spring boot项目设置了顶层域名的cookie之后,子域名web端获取不到设置的cookie,帮其解决。
模拟环境:
spring boot项目中,在某个Filter里设置顶层域名cookie:
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
Cookie cookie = new Cookie("test", "SG1");
cookie.setDomain(".localhost.com");
cookie.setPath("/");
配置访问子域名:
127.0.0.1 a.localhost.com
可惜的是不过关:
浏览器访问错误信息提示:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Thu Aug 16 23:35:53 CST 2018
There was an unexpected error (type=Internal Server Error, status=500).
An invalid domain [.localhost.com] was specified for this cookie
域名名字非法,但api说的是支持:
/**
* Specifies the domain within which this cookie should be presented.
* <p>
* The form of the domain name is specified by RFC 2109. A domain name
* begins with a dot (<code>.foo.com</code>) and means that the cookie is
* visible to servers in a specified Domain Name System (DNS) zone (for
* example, <code>www.foo.com</code>, but not <code>a.b.foo.com</code>). By
* default, cookies are only returned to the server that sent them.
*
* @param pattern
* a <code>String</code> containing the domain name within which
* this cookie is visible; form is according to RFC 2109
* @see #getDomain
*/
public void setDomain(String pattern) {
domain = pattern.toLowerCase(Locale.ENGLISH); // IE allegedly needs this
}
经搜索,及spring boot文档https://docs.spring.io/spring-boot/docs/2.0.3.RELEASE/reference/htmlsingle/#howto-use-tomcat-legacycookieprocessor 得知,这种域名设置是cookie 版本0的遗留格式,而spring boot 的嵌入式tomcat默认不支持,必须配置
LegacyCookieProcessor,即:
@Bean
public WebServerFactoryCustomizer<TomcatServletWebServerFactory> cookieProcessorCustomizer() {
return (factory) -> factory.addContextCustomizers(
(context) -> context.setCookieProcessor(new LegacyCookieProcessor()));
}
才能兼容这种格式。
为什么使用这种格式设置呢,为了是子域名也能读到cookie。
配置:
/**
* @author sdcuike
* @date 2018/8/16
* @since 2018/8/16
*/
@Configuration
public class CookieConfig {
/**
* 解决问题:
* There was an unexpected error (type=Internal Server Error, status=500).
* An invalid domain [.localhost.com] was specified for this cookie
*
* @return
*/
@Bean
public WebServerFactoryCustomizer<TomcatServletWebServerFactory> cookieProcessorCustomizer() {
return (factory) -> factory.addContextCustomizers(
(context) -> context.setCookieProcessor(new LegacyCookieProcessor()));
}
}
验证一下,cookie是不是在该域名可以看的到:
当然,和cookie版本的问题不仅仅是域名格式问题,cookie的大小限制(自动截取)也可能你也会碰到(在新浪彩票的时候,前端的同学遇到过)
代码: