This commit is contained in:
Marcel Pociot 2018-11-23 00:21:46 +01:00
parent c9b9d488ab
commit c9a4b68728
3 changed files with 63 additions and 1 deletions

View File

@ -2,6 +2,11 @@
return [ return [
'allowedOrigins' => [
'127.0.0.1',
'localhost',
],
/* /*
* Define the optional SSL context for your websocket connections. * Define the optional SSL context for your websocket connections.
* You can see all available options at: http://php.net/manual/en/context.ssl.php * You can see all available options at: http://php.net/manual/en/context.ssl.php

View File

@ -0,0 +1,55 @@
<?php
namespace BeyondCode\LaravelWebsockets\Server;
use Ratchet\ConnectionInterface;
use Ratchet\Http\CloseResponseTrait;
use Ratchet\Http\HttpServerInterface;
use Ratchet\MessageComponentInterface;
use Psr\Http\Message\RequestInterface;
class OriginCheck implements HttpServerInterface {
use CloseResponseTrait;
/** @var \Ratchet\MessageComponentInterface */
protected $_component;
protected $allowedOrigins = [];
public function __construct(MessageComponentInterface $component, array $allowedOrigins = []) {
$this->_component = $component;
$this->allowedOrigins = $allowedOrigins;
}
public function onOpen(ConnectionInterface $connection, RequestInterface $request = null) {
if ($request->hasHeader('Origin')) {
$this->verifyOrigin($connection, $request);
}
return $this->_component->onOpen($connection, $request);
}
function onMessage(ConnectionInterface $from, $msg) {
return $this->_component->onMessage($from, $msg);
}
function onClose(ConnectionInterface $connection) {
return $this->_component->onClose($connection);
}
function onError(ConnectionInterface $connection, \Exception $e) {
return $this->_component->onError($connection, $e);
}
protected function verifyOrigin(ConnectionInterface $connection, RequestInterface $request)
{
$header = (string)$request->getHeader('Origin')[0];
$origin = parse_url($header, PHP_URL_HOST) ?: $header;
if (! empty($this->allowedOrigins) && !in_array($origin, $this->allowedOrigins)) {
return $this->close($connection, 403);
}
}
}

View File

@ -74,7 +74,9 @@ class WebSocketServer
$router = new Router($urlMatcher); $router = new Router($urlMatcher);
$httpServer = new HttpServer($router); $app = new OriginCheck($router, config('websockets.allowedOrigins', []));
$httpServer = new HttpServer($app);
return new IoServer($httpServer, $socket, $this->loop); return new IoServer($httpServer, $socket, $this->loop);
} }