java - Spring Boot中跨子域共享cookie

标签 java spring-boot tomcat cookies subdomain

我有一个托管在 https://example.com 的 Web 应用程序。我想在主域 https://example.com 之间共享 session cookie 和子域 https://www.example.com 。因此,如果用户从一个域切换到另一个域,则不需要重新登录。如何在 springboot 2.2.6 中实现这一点?

这是我尝试过的: 我转到 application.properties 并设置 server.servlet.session.cookie.domain=.example.com 现在,这没有帮助。我收到错误:

java.lang.IllegalArgumentException: An invalid domain [.example.com] was specified for this cookie
    at org.apache.tomcat.util.http.Rfc6265CookieProcessor.validateDomain(Rfc6265CookieProcessor.java:210) ~[tomcat-embed-core-9.0.33.jar:9.0.33]
    at org.apache.tomcat.util.http.Rfc6265CookieProcessor.generateHeader(Rfc6265CookieProcessor.java:145) ~[tomcat-embed-core-9.0.33.jar:9.0.33]
    at org.apache.catalina.connector.Response.generateCookieString(Response.java:973) ~[tomcat-embed-core-9.0.33.jar:9.0.33]

如果我设置server.servlet.session.cookie.domain=example.com,则 cookie 对 http://www.example.com 不可见如果我设置 server.servlet.session.cookie.domain=www.example.com,则 http://example.com 的 cookie 不可见

我已阅读有关 Rfc6265CookieProcessor 和 LegacyCookieProcessor 的讨论,但我不知道解决此问题的正确方法。

Springboot 2.2.6使用tomcat版本9.0.*

那么,我该如何解决这个问题呢?

编辑:

我仅在本地主机上尝试上述更改,而不是在生产环境中。而不是访问http://www.example.com ,我在做https://www.localhost而不是访问 http://example.com ,我在做http://localhost

最佳答案

正确的值为:

server.servlet.session.cookie.domain=example.com

我尝试的是在本地主机上进行更改,但它们对我不起作用。我正在手动修改 chrome 控制台中的值,并期望看到在 https://localhost 上设置的 cookie,其中域 localhost 在域 https://www.localhost 的另一个选项卡中可见。但这并没有发生。

我在这里阅读了答案:Share cookie between subdomain and domain @Cesc 对该答案的评论是:

I am not sure where to put this so I am choosing the comments of the accepted answer. It took long time and failed experiments to prove the above on my localhost, until it occurred to me that I should call the localhost with a dot in the name. Like "localhost.com" or something like that. Then all the "set cookies" behaviours started following the explanations written here in this answer. Hoping this might help somebody.

所以,我直接在生产中尝试了我的更改,并且效果很好。我仍然无法让它在本地主机上工作。我在本地主机上访问我的网站的方式是:

https://localhost 和 https://www.localhost 。根据 @Cesc 的评论,我可能需要在本地主机上访问该网站 https://www.localhost.comhttps://localhost.com然后它就会起作用。但是,我没有尝试过。

关于java - Spring Boot中跨子域共享cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61154221/

相关文章:

html - 带有特殊字符的 ibatis 数据库名称

java - 使用 Java 中的 Logger 库登录文件时出现问题

java - 如何使用 GwtTestCase 测试带有 ui 绑定(bind)器的 gwt 复合组件?

java - Collections.reverse 不能正常工作

java - Spring JPA 的最低要求是什么

spring - 如何使用 Spring Boot 从不同的包中 Autowiring 存储库接口(interface)?

java - 服务器响应时间在负载测试期间变得非常慢

java - 正则表达式导致模式语法异常

java - java中Process中的字符串数组在参数中有空格

spring-boot - 服务实现 - 如何根据 application.properties 属性选择使用哪个服务实现?