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

时间:2016-03-10 08:37:29

标签: android cordova socket.io angular ionic2

我需要在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或运行离子run -l时,我确实有效 但当我只用buildrun离子运行的一切时,它都行不通。

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

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

1 个答案:

答案 0 :(得分:3)

问题与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几乎可以从任何地方出发。

相关问题