Fix API Rate Limit Exhaustion in Yii
Rate limit exhaustion is a critical vulnerability that enables brute-force attacks and resource depletion. In Yii2, many developers rely on default configurations which often omit the RateLimiter filter. To secure an API, you must implement the RateLimitInterface on your Identity class and attach the RateLimiter behavior to your controllers to enforce strict request quotas.
The Vulnerable Pattern
// Vulnerable: Identity model lacking RateLimitInterface class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface { public static function findIdentity($id) { return static::findOne($id); } // No rate limiting logic implemented here }
// Vulnerable: Controller without RateLimiter filter class ApiController extends \yii\rest\ActiveController { public $modelClass = ‘app\models\User’; // Default behaviors do not enforce limits if the Identity doesn’t implement the interface }
The Secure Implementation
The fix involves three components: 1. 'getRateLimit' defines the threshold (e.g., 100 requests/10 mins). 2. 'loadAllowance' and 'saveAllowance' persist the token bucket state. 3. The 'RateLimiter' behavior in the controller intercepts requests and returns a 429 Too Many Requests response when the bucket is empty. Pro-tip: For high-traffic APIs, move the allowance storage from MySQL to Redis to prevent database thrashing during a flood.
// Secure: Identity model implementing RateLimitInterface class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface, \yii\filters\RateLimitInterface { public function getRateLimit($request, $action) { return [100, 600]; // 100 requests per 600 seconds }public function loadAllowance($request, $action) { return [$this->allowance, $this->allowance_updated_at]; } public function saveAllowance($request, $action, $allowance, $timestamp) { $this->allowance = $allowance; $this->allowance_updated_at = $timestamp; $this->save(false, ['allowance', 'allowance_updated_at']); }}
// Secure: Controller explicitly enabling RateLimiter class ApiController extends \yii\rest\ActiveController { public function behaviors() { $behaviors = parent::behaviors(); $behaviors[‘rateLimiter’] = [ ‘class’ => \yii\filters\RateLimiter::class, ‘enableRateLimitHeaders’ => true, ]; return $behaviors; } }
Your Yii API
might be exposed to API Rate Limit Exhaustion
74% of Yii apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.