从不同的域读取 cookie [英] Reading a cookie from a different domain
问题描述
我正在为公司内部的活动开发页面/表单.但是,第一步是检查此人是否已登录.这很容易根据 cookie - CUSTOMER 进行检查,该 cookie 在他们登录后设置.
I'm developing a page/form for a campaign inside my company. However, the first step is to check if the person is logged in. This is easily checked against a cookie - CUSTOMER - that is set once they're logged in.
然而:1)我在本地开发,不在同一个域上,结果看不到那个cookie2) 最终活动可能会也可能不会驻留在实际域中.他们最终可能会使用虚 URL 或其他内容.
However: 1) I'm developing locally, not on the same domain, and, as a result can't see that cookie 2) The final campaign may or may not end up residing on the actual domain. They may end up using a vanity URL or something.
为此,我们假设我无权访问设置 cookie 的主域.
For purposes of this, let's assume I do NOT have access to the main domain where the cookie was set.
如何从域外读取该 cookie?哦,既然 IT 人员不让我们接触后端grumble,那么它必须是一个 JS 解决方案.
How can I read that cookie from off the domain? Oh, and since IT folks don't let us touch the back-end grumble, it has to be a JS solution.
谢谢!
推荐答案
你不能.
您可以使用客户端 JavaScript 读取的唯一 cookie 是那些属于 HTML 文档宿主的 cookie,其中嵌入了 .
The only cookies you can read with client side JavaScript are those belonging to the host of the HTML document in which the <script>
is embedded.
通过设置 withCredentials
你可以支持跨域请求中的 cookie,但它们由浏览器透明处理,JS 无法直接访问它们(XHR 规范甚至到 明确禁止 getAllResponseHeaders
读取与 cookie 相关的标头).跨域请求访问 cookie 的唯一方法是让服务器(您说您无权访问)将数据复制到正文或不同的响应标头中).
By setting withCredentials
you can support cookies in cross-origin requests, but they are handled transparently by the browser and JS has no direct access to them (the XHR spec goes to far as to explicitly ban getAllResponseHeaders
from reading cookie related headers). The only way for a cross-origin request to get access to cookies is for the server (which you say you don't have access to) to copy the data into the body or a different response header).
这篇关于从不同的域读取 cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!