You are viewing the documentation for the 1.x branch of the WebSocket Server package which has not yet been released. Be aware that the API for this version may change before release.
Reject Blocked IP Address Middleware
The BabDev\WebSocket\Server\Http\Middleware\RejectBlockedIpAddress class is a server middleware which can be used to reject connections from blocked IP addresses.
The middleware supports blocking either single addresses or subnet ranges from both IPv4 and IPv6 network ranges.
Addresses are matched against the connection's normalized remote_address attribute, so IPv4 clients connecting to a dual-stack server (one listening on [::]) are matched by their IPv4 address. Block these clients using IPv4 addresses and subnets, not their IPv4-mapped IPv6 form (::ffff:203.0.113.5).
The blocked address list can be updated at any time, including while the server is running.
Blocking an Address
To block an IP address, you can use the middleware's blockAddress() method:
<?php declare(strict_types=1);
use BabDev\WebSocket\Server\Http\Middleware\RejectBlockedIpAddress;
$middleware = new RejectBlockedIpAddress($decoratedMiddleware);
$middleware->blockAddress('192.168.1.1');
$middleware->blockAddress('192.168.1.0/24');
$middleware->blockAddress('::1');Allowing a Previously Blocked Address
To allow a previously blocked IP address, you can use the middleware's allowAddress() method:
<?php declare(strict_types=1);
use BabDev\WebSocket\Server\Http\Middleware\RejectBlockedIpAddress;
$middleware = new RejectBlockedIpAddress($decoratedMiddleware);
$middleware->blockAddress('192.168.1.1');
$middleware->blockAddress('192.168.1.0/24');
$middleware->allowAddress('192.168.1.0/24');Position in Middleware Stack
It is recommended that this middleware is decorated by the BabDev\WebSocket\Server\Http\Middleware\ParseHttpRequest middleware in your application (see the message flow section from the architecture documentation to see the recommended stack with all optional middleware). When the server is behind a reverse proxy, the connection's remote address is the proxy's IP address, so this middleware should instead be decorated by the BabDev\WebSocket\Server\Http\Middleware\ResolveForwardedClientAddress middleware, so blocked addresses are checked against the client's IP address.
As this middleware runs after the HTTP request is parsed, a blocked client's request is read before the connection is rejected; this is bounded by the request parser's maximum request size and the ParseHttpRequest middleware's request timeout.
It is also recommended that this middleware decorates the BabDev\WebSocket\Server\Http\Middleware\RestrictToAllowedOrigins middleware, but it can decorate any server middleware.