Rate-limit CI4 API endpoints with the built-in Throttler to block brute-force requests.
Throttling and Rate Limiting
// app/Filters/ThrottleFilter.php
use CodeIgniterThrottleThrottler;
class ThrottleFilter implements FilterInterface {
public function before(RequestInterface $request, $arguments = null) {
$throttler = service("throttler");
// 60 requests per minute per IP
if (!$throttler->check(
md5($request->getIPAddress()),
60, // capacity
MINUTE
)) {
return Services::response()
->setStatusCode(429)
->setJSON(["message" => "Too many requests. Wait " . $throttler->getTokenTime() . " seconds."]);
}
}
}
// Register in Config/Filters.php
public array $aliases = ["throttle" => ThrottleFilter::class];
// Apply to API routes
$routes->group("api", ["filter" => "throttle"], function($r) {
$r->resource("posts");
});