【问题标题】:How to stop CORB from blocking requests to data resources that respond with CORS headers?如何阻止 CORB 阻止对以 CORS 标头响应的数据资源的请求?
【发布时间】:2019-08-08 10:27:11
【问题描述】:

我正在开发一个 Chrome 扩展程序,它可以从某些网站向我控制的 API 发出请求。在 Chrome 73 之前,该扩展程序可以正常工作。升级到 Chrome 73 后,我开始收到以下错误:

跨源读取阻塞 (CORB) 阻止跨源响应 http://localhost:3000/api/users/1,MIME 类型为 application/json

根据Chrome's documentation on CORB,如果满足以下所有条件,CORB 将阻止请求的响应:

  1. 资源是“数据资源”。具体来说,内容类型是HTML、XML、JSON

  2. 服务器以 X-Content-Type-Options: nosniff 标头响应,或者如果省略此标头,Chrome 会通过检查文件检测到内容类型是 HTML、XML 或 JSON 之一

  3. CORS 未明确允许访问资源

另外,根据"Lessons from Spectre and Meltdown" (Google I/O 2018),似乎将mode: cors 添加到fetch 调用可能很重要,即fetch(url, { mode: 'cors' })

为了解决这个问题,我做了以下更改:

首先,我将以下标头添加到我的 API 的所有响应中:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Origin: https://www.example.com

其次,我更新了我对扩展程序的 fetch() 调用,如下所示:

fetch(url, { credentials: 'include', mode: 'cors' })

但是,这些更改不起作用。我可以进行哪些更改以使我的请求不会被 CORB 阻止?

【问题讨论】:

  • 在 Google 的特定扩展文章中查看解决方案,该文章是 different
  • 我认为如果你发布一个答案可能会更好——也许还有一些你认为相关的额外细节——因为你对此有更多的了解。我只知道这篇文章,不知道具体内容。
  • 虽然使用背景页面足以解决问题,但我仍然很困惑为什么 Chrome 会阻止我的扩展请求。 “更改 Chrome 扩展内容脚本中的跨域请求”一文写道,“为了减轻这些担忧,未来版本的 Chrome 将限制内容脚本与页面本身可以执行的相同获取。”这向我表明,跨域请求仍然可以从扩展中获得,但它们必须遵循 CORS。既然我将 CORS 标头添加到我的响应中,那么我的请求不应该成功吗?
  • 我也有兴趣回答这个问题。启用了 NetworkService 的 Chrome 73 似乎只是不对从内容脚本发出的 xhr 请求发出 CORS 预检请求,即使该请求需要 CORS 并且如果从主机页面发出会触发预检请求。这可能是Chrome错误吗?根据文档,他们的目的是使内容脚本“遵守与它们在其中运行的页面相同的请求规则”。如果从页面发出的 x-origin 请求触发了预检,但来自内容脚本的请求却没有,这似乎破坏了这个意图

标签: google-chrome google-chrome-extension cors cross-origin-read-blocking


【解决方案1】:

基于"Changes to Cross-Origin Requests in Chrome Extension Content Scripts" 中的示例,我将fetch 的所有调用替换为具有类似API 的新方法fetchResource,但将fetch 调用委托给后台页面:

// contentScript.js
function fetchResource(input, init) {
  return new Promise((resolve, reject) => {
    chrome.runtime.sendMessage({input, init}, messageResponse => {
      const [response, error] = messageResponse;
      if (response === null) {
        reject(error);
      } else {
        // Use undefined on a 204 - No Content
        const body = response.body ? new Blob([response.body]) : undefined;
        resolve(new Response(body, {
          status: response.status,
          statusText: response.statusText,
        }));
      }
    });
  });
}

// background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  fetch(request.input, request.init).then(function(response) {
    return response.text().then(function(text) {
      sendResponse([{
        body: text,
        status: response.status,
        statusText: response.statusText,
      }, null]);
    });
  }, function(error) {
    sendResponse([null, error]);
  });
  return true;
});

这是我能够对我的应用进行的最小的一组更改,以解决该问题。 (注意,扩展和后台页面之间只能传递 JSON-serializable 对象,所以我们不能简单地将 Fetch API Response 对象从后台页面传递给扩展。)

后台页面不受 CORS 或 CORB 影响,因此浏览器不再阻止来自 API 的响应。

【讨论】:

  • 我不确定使用response.text()new Blob([response.body]) 是否是重建 Response 对象的最忠实方法,但它适用于我只处理 JSON 响应的应用程序。我也不确定如何通过标题。
  • 虽然第三方组件调用自己的 API,我们能做些什么:/
  • 漂亮、可复制和可粘贴的代码。顺便说一句,你应该接受这个作为答案。
  • 不知道为什么,但从 Chrome 81 开始,情况似乎并非如此。 CORS 似乎禁止后台脚本进行fetch 调用
  • 通过此更改,我收到此错误:未检查的 runtime.lastError:消息端口在收到响应之前关闭。有什么想法可以解决这个问题吗?
【解决方案2】:

https://www.chromium.org/Home/chromium-security/extension-content-script-fetches

为了提高安全性,自 Chrome 85 起,Chrome 扩展程序禁止从内容脚本进行跨域提取。此类请求可以改为从扩展程序后台脚本发出,并在需要时中继到内容脚本。

您可以这样做以避免跨域。

旧内容脚本,进行跨域抓取:

var itemId = 12345;
var url = "https://another-site.com/price-query?itemId=" +
         encodeURIComponent(request.itemId);
fetch(url)
  .then(response => response.text())
  .then(text => parsePrice(text))
  .then(price => ...)
  .catch(error => ...)

新的内容脚本,要求其后台页面获取数据:

chrome.runtime.sendMessage(
    {contentScriptQuery: "queryPrice", itemId: 12345},
    price => ...);

新的扩展背景页面,从已知 URL 获取并中继数据:

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.contentScriptQuery == "queryPrice") {
      var url = "https://another-site.com/price-query?itemId=" +
              encodeURIComponent(request.itemId);
      fetch(url)
          .then(response => response.text())
          .then(text => parsePrice(text))
          .then(price => sendResponse(price))
          .catch(error => ...)
      return true;  // Will respond asynchronously.
    }
  });

允许 ma​​nifest.json 中的 URL (more info):

  • ManifestV2(经典):"permissions": ["https://another-site.com/"]
  • ManifestV3 (upcoming): "host_permissions": ["https://another-site.com/"]

【讨论】:

    【解决方案3】:

    临时解决方案:使用运行命令浏览器禁用 CORB --disable-features=CrossSiteDocumentBlockingAlways,CrossSiteDocumentBlockingIfIsolating

    Linux 上的示例运行命令。

    对于 Chrome:

    chrome %U --disable-features=CrossSiteDocumentBlockingAlways,CrossSiteDocumentBlockingIfIsolating

    对于 Chromium:

    chromium-browser %U --disable-features=CrossSiteDocumentBlockingAlways,CrossSiteDocumentBlockingIfIsolating

    Similar question.

    Source

    【讨论】:

    • 只要确保你没有告诉用户这样做。你想要安全。我唯一一次使用它是用于开发测试,而其他人正在同时解决 CORB 问题。
    猜你喜欢
    • 2019-07-21
    • 2019-01-22
    • 2018-12-01
    • 2021-06-12
    相关资源
    最近更新 更多