内容安全策略问题:Node.js与React

3

我正在使用Node.js开发React项目。我在我的index.html文件中有两个外部引用:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

除此之外,我还有一个发送到服务器的POST请求,由于CSP,连接失败了。具体的POST请求错误如下:

Refused to connect to 'localhost:3000/visitor' because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.

对于外部链接,我遇到了一些与内容安全策略相关的错误,其中之一在下面展示。

Refused to load the script 'https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js' because it violates the following Content Security Policy directive: "script-src 'self'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

我尝试了两种策略,但都没有解决我的问题:
  1. 元数据绕过:

在index.html文件中所有脚本标签之前添加元数据,以基本上开放任何类型的外部文件通过脚本标签加载,但仍然在浏览器中得到相同的错误,并且这些JS文件无法在我的应用程序中加载。

  1. 我在node.js中使用了helmet模块,如下所示:
app.use(helmet({

  contentSecurityPolicy: false,

}));

我应该怎么做才能解决这个问题,让应用程序能够正常运行?

1个回答

3

I did two strategies and none of the resolved my problem: 1- meta data by pass :

<meta http-equiv="Content-Security-Policy" content="...">

内容安全策略有两种传递方式:HTTP头和<meta>标签。您可以通过HTTP头实现一种严格的CSP,然后通过<meta>标签添加第二种CSP。这两种CSP会形成两个连续的过滤器,只有通过两者的源才会被允许。因此<meta>标签不会额外允许任何东西。相反,您需要将源添加到第一个CSP中,例如:

app.use(
  helmet({
    contentSecurityPolicy: {
      directives: {
        defaultSrc: ["'self'"], 
        scriptSrc: ["'self'", "'unsafe-inline'",  'https://ajax.googleapis.com', 'https://stackpath.bootstrapcdn.com'],
        styleSrc: ["'self'"],
        imgSrc: ["*", 'data:'],
        connectSrc: ["'self'"],
        frameSrc: ["'self'"],
      },
    }
  })
);

这个解决方法可以帮助解决第二个错误消息。

2- In my node js I used helmet module as the below :

app.use(helmet({
  contentSecurityPolicy: false,
}));

这将完全关闭CSP头,有助于避免Refused to load the script 'https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js' ...错误。

但第一个错误Refused to connect to 'localhost:3000/visitor' because it violates the following Content Security Policy directive: "default-src 'self'"仍然存在。
这是因为您的服务器上没有localhost:3000/visitor URL的路由,因此您会收到404未找到错误。

NodeJS finalhandler提供了自己的CSP default-src 'self'以确保安全性,因此您会发现CSP错误而不是由您管理。
/visitor URL创建正确的静态路由,此错误将消失。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接