【问题标题】:Content-Security-Policy with Ionic and Socket.IO带有 Ionic 和 Socket.IO 的内容安全策略
【发布时间】:2016-03-10 08:37:28
【问题描述】:

我需要在我的 ionic2 应用程序中使用 socket.io 连接。

我通过 npm 安装了 socket.io-client,所以我可以这样使用它。

import * as io from 'socket.io-client'
...
...
this.socket = io(this.conf.connectionServer);
this.socket.on('connect', () =>{
...
...})

当我在 chrome 中使用 ionic serve 或运行 ionic run -l 时,我确实可以工作 但是当我只是buildrun 离子运行的一切它不会工作。

我能够在我的安卓设备屏幕上记录错误信息:

Error: Failed to execute: open: on :XMLHttpRequest:: Refused to connect to : http://file/socket.io/?EIO.....: because it violates the documents Content Security Policy.....

我的内容安全政策是:

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

                    ;
        connect-src 'self'
                    ws://*
                    http://141.xx.xx.25:*
                    http://*.foobar.de
                    http://file/socket.io*
                    ;

        img-src *;
        media-src *
    ">

但我找不到合适的解决方案。我

在 Chrome 中,连接转到:http://141.XX.XX.25/socket.io/ 但在 android 上它会尝试连接到 http://file/socket.io/

即使我将其设置为 default-src *;,Socket.io-Connection 也仅在使用 Serverun with the Livereload-option 时才有效

我正在使用:

Cordova CLI: 6.0.0
Gulp version: CLI version 3.9.1
Gulp local:
Ionic Version: 2.0.0-beta.1
Ionic CLI Version: 2.0.0-beta.17
Ionic App Lib Version: 2.0.0-beta.8
OS:
Node Version: v5.6.0

【问题讨论】:

    标签: android cordova socket.io angular ionic2


    【解决方案1】:

    问题与 CSP 无关: 原因是socket.io连接的设置:

    //this is wrong
    this.statisticServer= "141.xx.xx.xx:8090/";
    ..
    this.socket = io(this.conf.connectionServer);
    

    但应该是:

    //this is right
    this.statisticServer= "http://141.xx.xx.xx:8090/";
    ...
    this.socket = io(this.conf.connectionServer);
    

    所以必须宣布 http 作为协议...可能是一个错误

    作为 CSP 可以使用:

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

    此 CSP 将允许来自任何地方的几乎所有内容。

    【讨论】:

      猜你喜欢
      • 2021-05-30
      • 1970-01-01
      • 2016-11-12
      • 2020-11-08
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多