Chrome 从远程站点请求localhost dev服务器时出现CORS错误

j2cgzkjk  于 2022-12-06  发布在  Go
关注(0)|答案(8)|浏览(510)

星期五我有一个正常的开发环境。星期一我有一个坏了的。我在Chrome开发工具控制台中遇到了这个错误消息:
CORS策略已阻止从源“http://www.example.com”访问位于“http://localhost:8080/build/app.css”的CSS样式表example.com:请求客户端不是安全上下文,资源位于更私有的地址空间local中。
有什么快速的解决方法吗?我试着在我的webpack devServer.headers配置中设置access-control-allow-origin,但是没有用:

config.devServer.headers = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'
}
kqqjbcuj

kqqjbcuj1#

Original Answer

I finally found the answer, in this RFC about CORS-RFC1918 from a Chrome-team member. To sum it up, Chrome has implemented CORS-RFC1918 , which prevents public network resources from requesting private-network resources - unless the public-network resource is secure (HTTPS) and the private-network resource provides appropriate (yet-undefined) CORS headers.
There's also a Chrome flag you can change to disable the new behavior for now: chrome://flags/#block-insecure-private-network-requests
Disabling that flag does mean you're re-opening the security hole that Chrome's new behavior is meant to close.

Update 2021: A few months after I posted this question, the flag I referenced in my original answer was removed, and instead of disabling a security feature I was forced to solve the problem more satisfactorily by serving assets over HTTPS.
Update 2022: Chrome 98 is out, and it introduces support for Preflight requests . According to the announcement, failed requests are supposed to produce a warning and have no other effect, but in my case they are full errors that break my development sites. So I had to add middleware to teach webpack-dev-server how to serve preflight requests.

Private Network Access (formerly CORS-RFC1918) is a specification that forbids requests from less private network resources to more private network resources. Like HTTP to HTTPS, or a remote host to localhost.
The ultimate solution was to add a self-signed certificate and middleware which enabled requests from my remote dev server to my localhost webpack-dev-server for assets.

Generate certificates

cd path/to/.ssl
npx mkcert create-cert

Configure webpack-dev-server to use certificates and serve preflight requests

module.exports = {
  //...
  devServer: {
    https: {
      key: readFileSync("./.ssl/cert.key"),
      cert: readFileSync("./.ssl/cert.crt"),
      cacert: readFileSync("./.ssl/ca.crt"),
    },

    allowedHosts: ".example.dev", // should match host in origin below
    setupMiddlewares(middlewares, devServer) {
      // Serve OPTIONS requests
      devServer.app.options('*', (req, res) => {
        // Only serve if request has expected origin header
        if (/^https:\/\/example\.dev$/.test(req.headers.origin)) {
          res.set({
            "Access-Control-Allow-Credentials": "true",
            "Access-Control-Allow-Private-Network": "true",
            // Using * results in error if request includes credentials
            "Access-Control-Allow-Origin": req.headers.origin,
          })

          res.sendStatus(200)
        }
      }

      return middlewares
    }
  }
}

Trust certificates

  1. Right click ca.crt in Windows Explorer and select Install Certificate
  2. Select Current User.
  3. Choose Place all certificates in the following store, then Browse..., and select Trusted Root Certification Authorities.
  4. Finish.
Firefox-specific instructions

Firefox doesn't respect your authoritah! by default. Configure it to do so with these steps:

  1. Type about:config into the address bar
  2. Search for security.enterprise_roots.enabled
  3. Toggle the setting to true
zzzyeukh

zzzyeukh2#

Chrome客户端忽略此警告并使资产可访问的方法:
1:转到chrome://flags/#block-insecure-private-network-requests
2:将**Block insecure private network requests**设置为禁用
注意:当您在自己的计算机或开发环境中使用时,这一功能可以正常工作

y4ekin9u

y4ekin9u3#

我能够允许从localhost到localhost的请求,并设置一个新的服务器头来进行预检和普通请求:

Access-Control-Allow-Private-Network: true

资料来源:
https://web.dev/cors-rfc1918-feedback/#step-2:-sending-preflight-requests-with-a-special-header

tag5nh1u

tag5nh1u4#

虽然Chrome现在保护用户免受跨站点请求伪造是件好事(CSRF)攻击的目标是专用网络上的路由器和其他设备,这也意味着依赖于对专用网络上资源的跨站点请求的合法应用程序(即业务应用程序)受到负面影响,需要进行更改。在我的公司,我们维护了一个通过HTTP公开的Web应用程序并调用客户端专用网络上标签打印机上的Web服务,并将其转发到专用网络上的Web服务。现在,我们将使此代理可供其他人使用:https://p2prox.io/

66bbxpm5

66bbxpm55#

我刚遇到这个问题,因为我在本地网络中的一个web服务器示例上遇到了同样的问题。这不一定是一个复杂的问题。例如,如果您包含来自公共资源的javascript库,如vue.js或node.js,则可能会发生这种情况。为了避免在本地网络中出现这种情况,请在本地服务器上存储库的副本,并在您的网页中引用它。例如,不要使用:

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.31/vue.global.min.js"></script>

使用了

<script src="./lib/vue.global.min.js"></script>
py49o6xq

py49o6xq6#

CORSsub.domain.com策略已阻止从源“http://sub.domain.com”访问位于“http://www.example.com/font/Sahel.css”的CSS样式表:请求客户端不是安全上下文,资源位于更私有的地址空间private中。
我正在为我工作的公司开发一个基于网络的系统,我们已经设置了dns和域,当我们在公司内部时可以本地访问系统,当我们不在公司时可以通过互联网访问系统。
上面的引用不时出现,并指同一个域作为一个在私人水平和其他作为一个较不私人!它将被修复的Ctrl + F5。如此荒谬!
在我的情况下,添加一个动态版本使用?v=时间()在年底的所有我的本地链接修复了我的问题,但它的成本下载所有脚本,CSS,字体每次用户加载页面!

iszxjhcz

iszxjhcz7#

临时解决方案。

Windows命令提示符下运行以下命令并重新启动chrome。

reg add HKEY_CURRENT_USER\SOFTWARE\Policies\Google\Chrome /t REG_DWORD /v InsecurePrivateNetworkRequestsAllowed /d 1 /f

参考:

https://developer.chrome.com/blog/private-network-access-update/
https://chromeenterprise.google/policies/#InsecurePrivateNetworkRequestsAllowed

trnvg8h3

trnvg8h38#

2022年12月更新

我想他们把国旗改名为...

  • 请尝试 *chrome://flags/#允许不安全的本地主机 *
  • 设置为启用
  • 重新启动Chrome

相关问题