【问题标题】:Geting error when trying to call API (Content Security Policy)尝试调用 API 时出错(内容安全策略)
【发布时间】:2020-03-23 12:45:04
【问题描述】:

尝试从已部署的网站启动get 函数并收到此错误:

Refused to connect to 'https://www.themealdb.com/api/json/v2/xxx/search.php?s=apple' because it violates the following Content Security Policy directive: "default-src 'self' http://*.google-analytics.com http://www.googletagmanager.com https://*.google.com https://*.google-analytics.com https://*.googletagmanager.com https://*.gstatic.com https://*.googleapis.com https://authedmine.com https://az743702.vo.msecnd.net https://sentry.io ws://localhost:4200". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.

在 localhost 服务器上运行网站时,一切正常。

将此meta tag 添加到我的index.html 并仍然收到相同的错误消息。

<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' http://* 'unsafe-inline'; script-src 'self' http://* 'unsafe-inline' 'unsafe-eval'">

【问题讨论】:

    标签: angular api httprequest content-security-policy httphandler


    【解决方案1】:

    所以,起初我为我的index.html 页面添加了元标记,但它没有用。 之后我创建了interceptor,将标题添加到我的get 函数中。 有关拦截器的更多信息,您可以在 https://angular.io/api/common/http/HttpInterceptor

    阅读

    还是不行。 然后我发现在我的 server.ts 文件中有这几行代码:

    app.use(helmet());
    app.use(helmet.contentSecurityPolicy({
      directives: AppConfig.cspDirectives
    }));
    

    。有关helmet 的更多信息: https://www.npmjs.com/package/helmet

    然后在我的 app.module providers 部分中分配了{provide: APP_CONFIG, useValue: AppConfig} 配置。

    下面是 app.config.ts 文件现在的样子:

    import {InjectionToken} from '@angular/core';
    
    export let APP_CONFIG = new InjectionToken('app.config');
    
    export const AppConfig: any = {
      cspDirectives: {
        defaultSrc: [
          '\'self\'',
          'http://*.google-analytics.com',
          'http://www.googletagmanager.com',
          'https://*.google.com',
          'https://*.google-analytics.com',
          'https://*.googletagmanager.com',
          'https://*.gstatic.com',
          'https://*.googleapis.com',
          'https://authedmine.com',
          'https://az743702.vo.msecnd.net',
          'https://sentry.io',
          'https://www.themealdb.com/',
          'ws:<my-webpage-url>',
        ],
        styleSrc: [
          '\'self\'',
          '\'unsafe-inline\'',
          'https://*.googleapis.com'
        ],
        scriptSrc: [
          '\'self\'',
          '\'unsafe-inline\'',
          'http://*.googletagmanager.com',
          'https://*.google-analytics.com'
        ]
      }
    };
    

    【讨论】:

      【解决方案2】:

      您应该检查您部署的网站正在发送哪些 CSP 响应标头。添加元标记只能限制 CSP 的总集合。

      您还试图连接到“”。如果您的预期 URL 在 CSP 中被列入白名单,但由于某种原因显示为空白,则可能是它失败的原因。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-07-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-07
        • 2016-06-22
        • 2021-09-15
        相关资源
        最近更新 更多