Cookie的path屬性不同對Cookie在不同瀏覽器的影響

關於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爲/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章