Final Class Yiisoft\Yii\Middleware\IpFilter
| Inheritance | Yiisoft\Yii\Middleware\IpFilter |
|---|---|
| Implements | Psr\Http\Server\MiddlewareInterface |
IpFilter allows access from specified IP ranges only and responds with 403 for all other IPs.
Public Methods
| Method | Description | Defined By |
|---|---|---|
| __construct() | Yiisoft\Yii\Middleware\IpFilter | |
| process() | Yiisoft\Yii\Middleware\IpFilter |
Method Details
| public mixed __construct ( \Yiisoft\Validator\ValidatorInterface $validator, \Psr\Http\Message\ResponseFactoryInterface $responseFactory, string|null $clientIpAttribute = null, array $ipRanges = [] ) | ||
| $validator | \Yiisoft\Validator\ValidatorInterface |
Client IP validator. The properties of the validator can be modified up to the moment of processing. |
| $responseFactory | \Psr\Http\Message\ResponseFactoryInterface |
The response factory instance. |
| $clientIpAttribute | string|null |
Name of the request attribute holding client IP. If there is no such
attribute, or it has no value, then the middleware will respond with 403 forbidden.
If the name of the request attribute is |
| $ipRanges | array |
Allowed IPv4 or IPv6 ranges. |
public function __construct(
/**
* @deprecated Will be removed in version 2.0. {@see IpRanges} from `network-utilities` package is used instead.
*/
ValidatorInterface $validator,
private readonly ResponseFactoryInterface $responseFactory,
private readonly ?string $clientIpAttribute = null,
array $ipRanges = [],
) {
$this->ipRanges = new IpRanges($ipRanges);
}
| public \Psr\Http\Message\ResponseInterface process ( \Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Server\RequestHandlerInterface $handler ) | ||
| $request | \Psr\Http\Message\ServerRequestInterface | |
| $handler | \Psr\Http\Server\RequestHandlerInterface | |
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
if ($this->clientIpAttribute !== null) {
$clientIp = $request->getAttribute($this->clientIpAttribute);
}
/** @psalm-var array{REMOTE_ADDR?: mixed} $serverParams */
$serverParams = $request->getServerParams();
$clientIp ??= $serverParams['REMOTE_ADDR'] ?? null;
if ($clientIp === null) {
return $this->createForbiddenResponse();
}
if (!is_string($clientIp) || !IpHelper::isIp($clientIp)) {
return $this->createForbiddenResponse();
}
if (!$this->ipRanges->isAllowed($clientIp)) {
return $this->createForbiddenResponse();
}
return $handler->handle($request);
}
Signup or Login in order to comment.