如何从Javascript设置的WebSocket Origin标?(How to set WebS

2019-10-23 01:52发布

我试图用JavaScript来让从本地一个网页套接字请求test.dev页面在IP上运行的服务器123.123.123.123代表的test.com 。 该请求通过,但123.123.123.123服务器发现的Origin: test.dev在WebSocket的请求头,并因为它希望看到拒绝连接Origin: test.com

这里是连接插座上的JavaScript代码:

ws = new WebSocket("123.123.123.123");

如何使用JavaScript来开始一个不诚实的一个WebSocket连接Origin的包头Origin: test.com

我希望像这样的工作,但我无法找到任何这样的:

ws = new WebSocket("123.123.123.123", "test.com");

Answer 1:

简单的解决办法是简单地创建您的一个条目hosts文件映射test.com123.123.123.123 。 当你要连接的“真正的”您需要稍后删除此项test.com

一个不太哈克解决方案将需要使用代理,可以重新写你的标题为你即时的。 考虑安装nginx系统上,然后代理方式的请求123.123.123.123藏在心里除了 Origin标相同。 下面是你需要在你的nginx的配置文件中的条目:

server {
    server_name test.dev;

    location / {
        proxy_pass http://123.123.123.123;
        proxy_set_header Origin test.com;

        # the following 3 are required to proxy WebSocket connections.
        # See more here: http://nginx.com/blog/websocket-nginx/

        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}


Answer 2:

如何使用JavaScript来开始一个不诚实的一个WebSocket连接Origin的包头Origin: test.com

如果我们能建立在JavaScript的请求的来源,同源策略不会在我们保持安全的非常好。 它只是存在,以保护我们不受这和其他潜在的攻击向量。

由于这个貌似开发工作,你使用web调试代理,如认为提琴手 (免费)或查尔斯 (支付)? 有了这些,你可以修改WebSocket的为自己的机器,或者是通过调试代理的任何试验机的初始握手请求或响应。



Answer 3:

一个好的解决办法是重写与其他的WebSocket库,如WebSocket的通话https://github.com/websockets/ws 。 要使用该库的Node.js在浏览器中,你只需要使用http://browserify.org/ 。



Answer 4:

如果你真的必须建立一个假的“出身”头从JavaScript值-有一种方法。 它不是你会发现在你公认的原则手册,但在这里它是:

创建调用插座,用假原点值的PHP文件。 现在请用ajax php文件,从你的JavaScript。

它可能不是优雅,道德还是可以接受的,但从来没有接受任何人告诉你,它不能做。

“send.php”使用AJAX从JavaScript叫

send.php内容

require "websocket_client.php";
$client = new Client("IP_ADDR:PORT", $_GET[mobile] ."|".$_GET[login]);
$client->send('1112223333|sms');
$client->send(json_encode(array('login'=>$user,'msg'=>$msg)));
echo $client->receive();`enter code here`

websocket_client.php是一个类文件基本的WebSocket功能(包括自定义原点值

 /**


 * Perform WebSocket handshake
   */
  protected function connect() {
    $url_parts = parse_url($this->socket_uri);
    $scheme    = $url_parts['scheme'];
    $host      = $url_parts['host'];
    $user      = isset($url_parts['user']) ? $url_parts['user'] : '';
    $pass      = isset($url_parts['pass']) ? $url_parts['pass'] : '';
    $port      = isset($url_parts['port']) ? $url_parts['port'] : ($scheme === 'wss' ? 443 : 80);
    $path      = isset($url_parts['path']) ? $url_parts['path'] : '/';
    $query     = isset($url_parts['query'])    ? $url_parts['query'] : '';
    $fragment  = isset($url_parts['fragment']) ? $url_parts['fragment'] : '';

$path_with_query = $path;
if (!empty($query))    $path_with_query .= '?' . $query;
if (!empty($fragment)) $path_with_query .= '#' . $fragment;

if (!in_array($scheme, array('ws', 'wss'))) {
  throw new BadUriException(
    "Url should have scheme ws or wss, not '$scheme' from URI '$this->socket_uri' ."
  );
}

$host_uri = ($scheme === 'wss' ? 'ssl' : 'tcp') . '://' . $host;

// Open the socket.  @ is there to supress warning that we will catch in check below instead.
$this->socket = @fsockopen($host_uri, $port, $errno, $errstr, $this->options['timeout']);

if ($this->socket === false) {
  throw new ConnectionException(
    "Could not open socket to \"$host:$port\": $errstr ($errno)."
  );
}

// Set timeout on the stream as well.
stream_set_timeout($this->socket, $this->options['timeout']);

// Generate the WebSocket key.
$key = self::generateKey();

// Default headers (using lowercase for simpler array_merge below).
$headers = array(
  'host'                  => $host . ":" . $port,
  'user-agent'            => 'websocket-client-php',
  'connection'            => 'Upgrade',
  'upgrade'               => 'websocket',
  'origin'               =>  $MY_CUSTOM_SHADY_VALUE,
  'sec-websocket-key'     => $key,
  'sec-websocket-version' => '13',
);

// Handle basic authentication.
if ($user || $pass) {
  $headers['authorization'] = 'Basic ' . base64_encode($user . ':' . $pass) . "\r\n";
}

// Deprecated way of adding origin (use headers instead).
if (isset($this->options['origin'])) $headers['origin'] = $this->options['origin'];

// Add and override with headers from options.
if (isset($this->options['headers'])) {
  $headers = array_merge($headers, array_change_key_case($this->options['headers']));
}

$header =
  "GET " . $path_with_query . " HTTP/1.1\r\n"
  . implode(
    "\r\n", array_map(
      function($key, $value) { return "$key: $value"; }, array_keys($headers), $headers
    )
  )
  . "\r\n\r\n";

// Send headers.
$this->write($header);

// Get server response.
$response = '';
do {
  $buffer = stream_get_line($this->socket, 1024, "\r\n");
  $response .= $buffer . "\n";
  $metadata = stream_get_meta_data($this->socket);
} while (!feof($this->socket) && $metadata['unread_bytes'] > 0);

/// @todo Handle version switching

// Validate response.
if (!preg_match('#Sec-WebSocket-Accept:\s(.*)$#mUi', $response, $matches)) {
  $address = $scheme . '://' . $host . $path_with_query;
  throw new ConnectionException(
    "Connection to '{$address}' failed: Server sent invalid upgrade response:\n"
    . $response
  );
}

$keyAccept = trim($matches[1]);
$expectedResonse
  = base64_encode(pack('H*', sha1($key . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));

if ($keyAccept !== $expectedResonse) {
  throw new ConnectionException('Server sent bad upgrade response.');
}

$this->is_connected = true;

}



文章来源: How to set WebSocket Origin Header from Javascript?