使用 Ionic 和 Socket.IO 的内容安全策略

Content-Security-Policy with Ionic and Socket.IO

我需要在我的 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 或 运行ning ionic run -l 时,我会工作 但是当我只是 buildrun 所有带有 ionic 运行 的东西都不起作用时。

我能够在我的 android 设备的屏幕上记录错误消息:

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 *
    ">

但是我找不到合适的solution.I

在 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

该问题与 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 将允许来自任何地方的几乎所有内容。