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

本文探讨了Cookie在不同浏览器中的表现差异,特别是在Chrome与Firefox之间的Path属性处理方式的不同。通过一个具体的SpringBoot应用实例,解释了如何正确设置Cookie的Path属性以确保跨子域的一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于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为/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值