我有一个托管在 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.com或https://localhost.com然后它就会起作用。但是,我没有尝试过。
关于java - Spring Boot中跨子域共享cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61154221/