首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何正确设置helmet.js以解决CSP问题?

如何正确设置helmet.js以解决CSP问题?
EN

Stack Overflow用户
提问于 2020-11-10 10:45:01
回答 2查看 2.6K关注 0票数 2

当我启动我的express应用程序时,浏览器给我这个错误:

代码语言:javascript
复制
Refused to load the script 'http://localhost:1337/main.js' because it violates
the following Content Security Policy directive: "script-src unsafe-eval".
Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

在我的index.js文件中,我设置了如下头盔:

代码语言:javascript
复制
// Set Content Security Policies
const scriptSources = ["'self'", "'unsafe-inline'", "'unsafe-eval'"];
const styleSources = ["'self'", "'unsafe-inline'"];
const connectSources = ["'self'"];

app.use(
  helmet.contentSecurityPolicy({
    defaultSrc: ["'self'"],
    scriptSrc: scriptSources,
    scriptSrcElem: scriptSources,
    styleSrc: styleSources,
    connectSrc: connectSources,
    reportUri: '/report-violation',
    reportOnly: false,
    safari5: false  
  })
);
app.use(helmet({
  contentSecurityPolicy: false,
}));

在.js文件中加载我的index.html,如下所示:

代码语言:javascript
复制
<script type="module" src="./main.js"></script>

这是我的GitHub回购:https://github.com/jgonzales394/fsn.pw

EN

回答 2

Stack Overflow用户

发布于 2020-11-10 11:44:54

头盔维修员。这是因为您的指令需要嵌套在directives属性下。

例如:

代码语言:javascript
复制
app.use(
  helmet.contentSecurityPolicy({
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: scriptSources,
      // ...
    },
  })
)
票数 1
EN

Stack Overflow用户

发布于 2020-11-12 03:28:24

好的,我设法让它正常工作。头盔允许我这样设置我的CSP:

代码语言:javascript
复制
app.use(
  helmet.contentSecurityPolicy({
    defaultSrc: ["'self'"],
    scriptSrc: scriptSources,
    scriptSrcElem: scriptSources,
    styleSrc: styleSources,
    connectSrc: connectSources,
    reportUri: '/report-violation',
    reportOnly: false,
    safari5: false  
  })
);

所以我的main.js文件是一个vue应用程序,我之前写的是这样的:

代码语言:javascript
复制
import * as Vue from './src/vue.esm-browser.js';

const App = Vue.createApp({
  data() {
    return {
      slug,
      url
    }
  },
  methods: {
    createUrl() {
      console.log(this.slug, this.url);
    }
  }
}).mount('#app');

我重写了代码,如下所示:

代码语言:javascript
复制
import { createApp, ref } from './src/vue.esm-browser.js';

const slug = ref('');
const url = ref('');

createApp({
 setup() {
   const createUrl = () => {
     console.log(slug.value, url.value);
   };

   return {
     slug,
     url,
     createUrl
   };
 }
}).mount('#app');

在我的html文件中,可以在不调用createUrl的情况下调用它。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64762132

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档