我正在尝试打开一个从chrome扩展到我的后端的经过身份验证的websocket连接,为此我使用了会话cookie。这是我的清单文件:
{
"manifest_version": 2,
"background": {
"scripts": ["extension.js"],
"persistent": true
},
"permissions": [
"tabs",
"storage",
"http://localhost:8000/",
"ws://localhost:8000/"
],
"icons": {
"16": "img/icon16.png",
"48": "img/icon48.png",
"128": "img/icon128.png"
}
}在那里,我请求允许在HTTP和websocket方案上访问localhost:8000,但是Chrome只为AJAX请求发送cookie。如果我尝试
await fetch('http://localhost:8000/checklogin', {
method: 'GET',
credentials: 'include'
});从后台脚本发送cookie,但如果我尝试
const ws = new WebSocket('ws://localhost:8000/');根本不会发送cookie。
不是同一个域名,为什么Chrome不为websocket发送cookie?
发布于 2021-09-20 18:24:42
根据我的研究,我得出结论,带有websocket凭据的CORS在chrome扩展中不受支持,因此Chrome不会在websocket升级请求中注入凭据。解决方法是使用chrome.webRequest截获websocket升级请求并注入Cookie标头:
class WebsocketCookie {
constructor(websocketUrl, name, value) {
this.name = name;
this.value = value;
chrome.webRequest.onBeforeSendHeaders.addListener(
({ requestHeaders }) => {
requestHeaders.push({name: 'Cookie', value: `${this.name}=${this.value}`});
return {requestHeaders};
},
{types: ['websocket'], urls: [websocketUrl]},
['blocking', 'requestHeaders', 'extraHeaders']
);
}
}
// you can change this cookie later by changing cookie.name or cookie.value
const cookie = new WebsocketCookie('ws://localhost:8000/', 'sessionid', 'my_session_id');
const ws = new WebSocket('ws://localhost:8000/'); // sessionid cookie will be injected这需要将websocket URL、webRequest和webRequestBlocking权限添加到清单文件。使用chrome.cookies获取需要在websocket升级请求中注入的cookies。
如果你想提高安全性,onBeforeSendHeaders回调会将该请求的来源作为initiator成员,用它来检查来源是否是你自己的分机。您可以使用chrome.management接口获取您的扩展的来源。
https://stackoverflow.com/questions/69247283
复制相似问题