具有内联样式的 svg 的内容安全策略

content security policy for svg with inline style

我有以下 svg 图片:

<svg viewBox="0 0 679.26666 170.12"><title id="title">Disclosure Scotland</title>
  <desc id="descA">Main Image</desc><defs id="defs6"></defs><g transform="matrix(1.3333333,0,0,-1.3333333,0,170.12)" id="g10">
     <g transform="scale(0.1)" id="g12">
         <path id="path14" style="fill:#354a8e;fill-opacity:1;fill-rule:nonzero;stroke:none" d="L 4424.6,237.121">
         </path>
     </g>

 </svg>

它有内联样式,内容安全策略抱怨以下警告:

Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-n9prShQTue5kpNbWK2Rpxv1agUjurIm2Wkpn0y7gOvU='), or a nonce ('nonce-...') is required to enable inline execution.

10localhost/:13 Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-hyCd2mGzJH6FFMa/YKxkUO5p7ntTtWZ4+813FvHVP5w='), or a nonce ('nonce-...') is required to enable inline execution.

我可以通过像这样配置 styleSrc 来消除该错误:

app.use(
  helmet.contentSecurityPolicy({
    directives: {
      defaultSrc: ["'self'"],
      styleSrc: ["'self'", "'unsafe-inline'"]
    }
  })
);

我可以为 svg 配置内联样式吗?

不是专门针对 SVG,不是。 CSP 不允许这种类型的精细控制。您可以做的是:

1) 使用 CSP 随机数

2) 使用 类 或 ID(以及样式表中相应的 CSS)

3) 使用JavaScript直接修改CSS

解决这个问题的最简单方法是直接添加属性,而不是使用内联样式;

     <path id="path14" style="fill:#354a8e;fill-opacity:1;fill-rule:nonzero;stroke:none" d="L 4424.6,237.121">

至:

     <path id="path14" fill="#354a8e" fill-opacity="1" fill-rule="nonzero" stroke="none" d="L 4424.6,237.121">