与Express(带头盔)一起使用create-react-app创建的应用程序投放时,CSP错误 [英] CSP error while serving with express (with helmet) an app created with create-react-app

查看:67
本文介绍了与Express(带头盔)一起使用create-react-app创建的应用程序投放时,CSP错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力提供使用"create-react-app"创建的版本与头盔一起使用Express.我在资源管理器控制台中遇到与内容安全策略"相关的几个错误:

I'm struggling with serving a build created with "create-react-app" using Express with Helmet. I'm getting several errors in the explorer console related to Content Security Policy:

csp错误

当然,它不会显示该应用程序.我注意到,如果在Express中将头盔移除为中间件可以工作,但这不是我想要的解决方案.这是我的服务器代码:

Of course, it isn't showing the app. I noticed that if a remove Helmet as middleware in Express it works but that's not the solution I want. This is my server code:

const express = require('express');
const helmet = require('helmet');
const cors = require('cors');
const morgan = require('morgan');
const bodyParser = require('body-parser');

/**
 * Server Configuration
 */

const whitelist = [];

const app = express();

// Express Configurations

// Enable reverse proxy support in Express. This causes the the "X-Forwarded-Proto" header field to be trusted so its
// value can be used to determine the protocol. See // http://expressjs.com/api#app-settings for more details.

app.enable('trust proxy');

app.use(morgan('dev')); // Log every request to the console
app.use(helmet()); // Configure secure Headers
app.use(bodyParser.urlencoded({ extended: false })); // Enable parsing of http request body
app.use(bodyParser.json());

// CORS Configuration

const corsOptions = {
  origin: (origin, callback) => {

    if (whitelist.indexOf(origin) !== -1 || !origin) {

      callback(null, true);

    } else {

      callback(new Error('Not allowed by CORS'));

    }

  },
};

app.use(cors(corsOptions)); // Allow CORS

/**
 * Launcher method
 */

app.start = () => {

  // start node server
  const port = process.env.PORT || 3000;
  app.listen(port, () => {

    console.log(`App UI available http://localhost:${port}`);
    console.log(
      `Swagger UI available http://localhost:${port}/swagger/api-docs`,
    );

  });

};

/**
 * App Initialization
 */

function initializeApp(readyCallback) {

  readyCallback(null, app);

}

module.exports = (readyCallback) => {

  initializeApp(readyCallback);

};

有人可以帮我吗?预先感谢!

Can anyone give me a hand? Thanks in advance!

推荐答案

此处是头盔维护者.

之所以发生这种情况,是因为有一个称为内容安全策略"的内容,安全帽默认设置了该内容.要解决您的问题,您将需要配置Helmet的CSP.

This is happening because of something called Content Security Policy, which Helmet sets by default. To solve your problem, you will need to configure Helmet's CSP.

MDN拥有有关CSP的很好的文档,我会建议阅读背景知识.之后,请查看头盔的自述文件,以了解如何配置其CSP组件.

MDN has a good documentation about CSP which I would recommend reading for background. After that, take a look at Helmet's README to see how to configure its CSP component.

要针对此问题提供一些帮助,让我们看一下您看到的一个错误:

To give some help specific to this question, let's take a look at one error you're seeing:

Content Security Policy: This page's settings blocked the loading of a resource at inline ("script-src").

此错误告诉您CSP的 script-src 指令不允许内联JavaScript,因此已被阻止.

This error is telling you that the script-src directive of your CSP does not allow inline JavaScript, and so it was blocked.

这被认为是内联"的.JavaScript:

This is considered "inline" JavaScript:

<script>console.log('hello world!')</script>

但是,这不是:

<script src="/foo.js"></script>

有几种方法可以解决此问题:

There are several ways to fix this:

  1. 向内联< script> 中添加哈希或随机数,并在CSP中使用它们.请参见有关MDN的示例寻求帮助.

  1. Add a hash or nonce to the inline <script> and use that in your CSP. See this example on MDN for help.

重构您的应用,以完全避免使用内联脚本.

Refactor your app to avoid inline scripts entirely.

更新您的CSP以允许使用不安全的内联脚本.您将执行以下操作:

Update your CSP to allow unsafe inline scripts. You'd do something like this:

app.use(
  helmet({
    contentSecurityPolicy: {
      directives: {
        ...helmet.contentSecurityPolicy.getDefaultDirectives(),
        "script-src": ["'self'", "'unsafe-inline'", "example.com"],
      },
    },
  })
);

请注意,这被认为是不安全的.

Note that this is considered unsafe.

禁用CSP.这是最危险的选择,所以我不建议这样做.

Disable CSP. This is the most dangerous option so I don't recommend it.

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

您的其他错误,例如 fonts.googleapis.com 错误,请参考 default-src ,如果未指定指令,这是后备方法.

Your other errors, such as the fonts.googleapis.com error, refer to default-src, which is the fallback if a directive is not specified.

总结:要解决您的问题,您需要告诉Helmet配置您的CSP.

In summary: to solve your problem, you will need to tell Helmet to configure your CSP.

这篇关于与Express(带头盔)一起使用create-react-app创建的应用程序投放时,CSP错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆