Nuxt + Vuetify 使用内容安全策略 (CSP) header 内联样式

Nuxt + Vuetify using Content Security Policy (CSP) header inline styling

对于我的公司,我需要更新我们的 Nuxt + Vuetify 应用程序以使用内容安全策略 (CSP) header。 'unsafe-inline' 不允许用于 'default-src'。我们目前面临的问题是 Vuetify 在运行时将样式属性添加到 DOM 元素。

例如:

<div id="app">
  <v-system-bar app>
    <v-container>Content</v-container>
  </v-system-bar>
</div>

结果:

<div class="v-system-bar v-system-bar--fixed theme--light" style="height: 24px;">
    <div class="container">Content</div>
</div>

CSP header 不允许 style="height: 24px"。这给了我以下错误:

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

其他 vuetify 组件也会出现此问题,v-system-bar 只是一个示例。我知道可以为 <style> 元素添加随机数,但不能为 style 属性添加随机数。除了将 header 设置为 unsafe-inline 之外,有没有办法解决这个问题?我想继续将 Vuetify 与 CSP 一起使用 header.

这是一个代码笔link:https://codepen.io/erikeuserr/pen/WNpbOwx

提前致谢!

style="height: 24px"这样的结构出现在代码中作为vue.js的结果(不是vuetify.js) 脚本工作。 vue.js 使用 el.setAttribute() 函数设置 style= 属性。 el.setAttribute('style', ...) 被 CSP 视为不安全,因此 vue.js 与 CSP 不兼容。

但是 el.style.property = '...' 是安全的,所以为了使 vue.js 与 CSP 兼容,需要将所有 el.setAttribute('style', 'background-color:#e2e2e2; height: 24px; display:inline;') 替换为照套数:

el.style.backgroundColor = '#e2e2e2';
el.style.height = '24px';
el.style.display = 'inline';
  1. 有一个 rough hack 可以做到这一点 - 在使用 'style' 参数调用时全局重新定义 setAttribute()

  2. 在将页面输出到浏览器之前,您可以在 html 代码中将所有 style='...' 捕获并替换为 data-style='...',然后使用如下脚本:

    styleList = document.querySelectorAll("[data-style]");
    styleList.forEach( function(style) {
    // convert a 'background-color:#e2e2e2; height: 24px; display:inline;' strings
    // to the set of 'el.style.backgroundColor = '#e2e2e2'; ... el.style.display = 'inline';'<br> });`

是的,这些是补丁,但是了解了问题的本质,你或许可以找到更优雅的解决方案。