diff --git a/config/config.php b/config/config.php index c6b9665..abd70ae 100644 --- a/config/config.php +++ b/config/config.php @@ -2,6 +2,11 @@ return [ + 'allowedOrigins' => [ + '127.0.0.1', + 'localhost', + ], + /* * Define the optional SSL context for your websocket connections. * You can see all available options at: http://php.net/manual/en/context.ssl.php diff --git a/src/Server/OriginCheck.php b/src/Server/OriginCheck.php new file mode 100644 index 0000000..9216375 --- /dev/null +++ b/src/Server/OriginCheck.php @@ -0,0 +1,55 @@ +_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); + } + } +} \ No newline at end of file diff --git a/src/Server/WebSocketServer.php b/src/Server/WebSocketServer.php index 67ecf04..47ec959 100644 --- a/src/Server/WebSocketServer.php +++ b/src/Server/WebSocketServer.php @@ -74,7 +74,9 @@ class WebSocketServer $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); }