Cookie的path属性不同对Cookie在不同浏览器的影响

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/russle/article/details/81463205

关于Cookie的官方介绍,请参考https://en.wikipedia.org/wiki/HTTP_cookie
Domain and path

The Domain and Path attributes define the scope of the cookie. They essentially tell the browser what website the cookie belongs to. For obvious security reasons, cookies can only be set on the current resource’s top domain and its sub domains, and not for another domain and its sub domains. For example, the website example.org cannot set a cookie that has a domain of foo.com because this would allow the example.org website to control the cookies of foo.com.

If a cookie’s Domain and Path attributes are not specified by the server, they default to the domain and path of the resource that was requested.[36] However, in most browsers there is a difference between a cookie set from foo.com without a domain, and a cookie set with the foo.com domain. In the former case, the cookie will only be sent for requests to foo.com, also known as a host-only cookie. In the latter case, all sub domains are also included (for example, docs.foo.com).[37][38] A notable exception to this general rule is Internet Explorer, which always sends cookies to sub domains regardless of whether the cookie was set with or without a domain.[39]

Below is an example of some Set-Cookie HTTP response headers that are sent from a website after a user logged in. The HTTP request was sent to a webpage within the docs.foo.com subdomain:

Cookie中Path简介
Path – 路径。指定与cookie关联的WEB页。值可以是一个目录,或者是一个路径。如果http://www.a.com/dir1/index.html 建立了一个cookie,那么在http://www.a.com/dir1/目录里的所有页面,以及该目录下面任何子目录里的页面都可以访问这个cookie。这就是说,在www.a.com/dir1/pages/a 里的任何页面都可以访问http://www.a.com/dir1/index.html 建立的cookie。但是,如果http://www.a.com/dir2/pages/ 需要访问http://www.a.com/dir1/index.html设置的cookes,该怎么办?这时,我们要把cookies的path属性设置成“/”。在指定路径的时候,凡是来自同一服务器,URL里有相同路径的所有WEB页面都可以共享cookies。现在看另一个例子:如果想让 http://www.a.com/dir1/devices/http://www.a.com/dir1/users/共享cookies,就要把path设成“/dir1”。

问题
我们使用SpringBoot开发,在controller中的rest get方法中设置了Cookie,前端js代码可以firefox上正常工作,但是在chrome上不行.

分析
分析后发现chrome上无法获取cookie,仔细对比发现是因为Spring Boot程序设置server.contextPath= /xxxx,这样在浏览器中可以看到当cookie的path为xxxx的只能在firefox中显示,chrome不能显示。最后决定强制将cookie的path设置为/

解决办法
主动在创建Cookie时,设置Cookies的path为/

猜你喜欢

转载自blog.csdn.net/russle/article/details/81463205