【问题标题】:Allowing S3 images with npm helmet允许带有 npm 头盔的 S3 图像
【发布时间】:2020-12-20 01:02:50
【问题描述】:

我正在使用 npm 头盔来保护我的 express 应用程序,但我想允许我的 S3 存储桶中的图像进行渲染。当我使用 helment Refused to load the image '<URL>' because it violates the following Content Security Policy directive: "img-src 'self' data:". 时出现此错误,这是有道理的,我违反了头盔实现的 CSP。

我能在他们的文档中找到的唯一内容是:

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

这确实允许我的图像渲染,但我仍然想要头盔提供的 CSP。我只需要基本上将我的 S3 链接列入白名单,但我在他们的文档中找不到关于此主题的任何内容

【问题讨论】:

  • 我目前也在处理类似的事情,经过研究,我正在接近app.use(helmet({contentSecurityPolicy: {directives:{...helmet.contentSecurityPolicy.getDefaultDirectives(),"img-src" : ["'self'", "data: https:"]}}}));

标签: node.js express amazon-s3 node-modules helmet.js


【解决方案1】:

这里是头盔的维护者。

默认情况下,Helmet 设置了几个与安全相关的标头,包括一个名为 Content-Security-Policy 的标头。内容安全政策(CSP)实际上是允许您的页面加载和执行的内容的许可名单。

您看到的错误表明您的 CSP 不允许从您的域 ('self') 或数据 URI (data:) 以外的任何地方加载图像。您可以通过以下方式解决此问题:

app.use(
  helmet({
    contentSecurityPolicy: {
      directives: {
        ...helmet.contentSecurityPolicy.getDefaultDirectives(),
        "img-src": ["'self'", "s3.amazonaws.com"],
      },
    },
  })
);

有关 CSP 的更多信息,请查看this introduction on MDN

这是我一直在考虑在 Helmet 的文档中更清楚地说明的内容,因此感谢您提出这个问题。

【讨论】:

  • 嘿,感谢您的回复,我尝试了该代码,但仍然遇到相同的错误; Refused to load the image '<URL>' because it violates the following Content Security Policy directive: "img-src 'self' data:".我尝试调整“s3.amazonaws.com”以匹配我的网址,但仍然没有运气
  • 我打错了; image-src 应该是 img-src
  • 嗨,evan,我很抱歉再次打扰您,我知道您可能很忙,所以请随意忽略此消息,但您提供的代码即使使用错字更正仍然无法正常工作。我'仍然收到原始错误消息
  • 哎呀抱歉,我刚刚修复了它.. 不得不稍微修改一下网址,抱歉打扰.. 感谢您维护这样一个很棒的包!
  • 没问题!很高兴我能帮上忙。
猜你喜欢
  • 2021-10-29
  • 2023-02-19
  • 1970-01-01
  • 2017-02-05
  • 2020-10-31
  • 1970-01-01
  • 2020-11-08
  • 1970-01-01
相关资源
最近更新 更多