(API) Rate limiting requests in CakePHP 3
- CakePHP 3.0+
- CakePHP cache engine with support for atomic updates
Please note that this plugin will not work when using the default CakePHP File Storage cache engine.
composer require muffin/throttle:dev-master
To make your application load the plugin either run:
./bin/cake plugin load Muffin/Throttle
or add the following line to config/bootstrap.php
:
Plugin::load('Muffin/Throttle');
In bootstrap.php
:
DispatcherFactory::add('Muffin/Throttle.Throttle');
This will use the defaults, 10 requests by minute for any given IP. You could easily change that by passing your own configuration:
DispatcherFactory::add('Muffin/Throttle.Throttle', [
'message' => 'Rate limit exceeded',
'interval' => '+1 hour',
'rate' => 300,
'identifier' => function (Request $request) {
if (null !== $request->header('Authorization')) {
return str_replace('Bearer ', '', $request->header('Authorization'));
}
return $request->clientIp();
}
]);
The above example would allow 300 requests/hour/token and would first try to identify the client by JWT Bearer token before falling back to (Throttle default) IP address based identification.
By default Throttle will add X-headers with rate limiting information to all responses:
X-RateLimit-Limit: 10
X-RateLimit-Remaining: 7
X-RateLimit-Reset: 1438434161
To customize the header names simply pass (all of them) to your configuration:
DispatcherFactory::add('Muffin/Throttle.Throttle', [
'headers' => [
'limit' => 'X-MyRateLimit-Limit',
'remaining' => 'X-MyRateLimit-Remaining',
'reset' => 'X-MyRateLimit-Reset'
]
]);
To disable the headers pass false
:
DispatcherFactory::add('Muffin/Throttle.Throttle', [
'headers' => false
]);
- Fork
- Mod, fix
- Test - this is important, so it's not unintentionally broken
- Commit - do not mess with license, todo, version, etc. (if you do change any, bump them into commits of their own that I can ignore when I pull)
- Pull request - bonus point for topic branches
To ensure your PRs are considered for upstream, you MUST follow the CakePHP coding standards.
http://github.com/usemuffin/throttle/issues
Copyright (c) 2015, [Use Muffin] and licensed under The MIT License.