Example of Laravel 5 limiting the frequency of calls to the API

Source: Internet
Author: User
Tags curl json iptables

What is the frequency limit?
The frequency limit is to control the number of requests in the unit time. It can be applied to ports, IP, routing, and so on, and if used properly, it can be very effective in organizing malicious attacks. Take our API as an example, it can reject DOS attacks, so it is not downtime when ordinary users visit.

Note that frequency limits can also be implemented through firewalls. For example, use the iptables in the Debian system:

> Iptables-i input-p tcp--dport 80-i eth0-m state--state new-m \
--set

> Iptables-i input-p tcp--dport 80-i eth0-m state--state new-m \
--update--seconds--hitcount 10-j DROP
This restricts access to port 80, 10 times per minute. However, it is difficult to implement a request that restricts only certain routes, not the entire Web site. Fortunately, Laravel (version 5.2) has built-in API throttling middleware for this requirement.

Laravel Frequency limit
First, let's create an API. The goal is to create a task through an API. It's simple, we just add two routes (lists and additions), we just return JSON data instead of a template page.

Route::group ([' prefix ' => ' api/v1 '], function () {

Route::get ('/gettasks ', function () {
return Task::all ();
});

Route::p ost ('/addtask ', function (Request $request) {
$validator = Validator::make ($request->all (), [
' Names ' => ' required|max:255 ',
]);

if ($validator->fails ()) {
return response ()->json ([' Error ' => $validator->messages ()],200);
}

$task = new Task;
$task->names = $request->names;
$task->save ();

return response ()->json ([' Response ' => ' Added {$request->names} to Tasks. "], 200);
});
});
Now we can add and display the task list through Curl:

> Curl-x post-h "Content-type:application/json"--data ' {names ': ' Make a Cake '} ' http://10.10.0.10:8880/api/v1/add Task

{"Response": "Added make a cake to tasks."}

> Curl Http://10.10.0.10:8880/api/v1/getTasks

[{"id": 7, "names": "Grocery shopping", "Created_at": "2016-05-12 06:18:46", "Updated_at": "2016-05-12 06:18:46"},{"id" : 8, "names": "Dry Cleaning", "created_at": "2016-05-12 06:18:52", "Updated_at": "2016-05-12 06:18:52"},{"id": "Names" : "Car Wash", "created_at": "2016-05-12 09:51:01", "Updated_at": "2016-05-12 09:51:01"},{"IDs": "Names": "Make a Cake", " Created_at ":" 2016-06-24 07:13:21 "," Updated_at ":" 2016-06-24 07:13:21 "}]
Make a cake task and created. Now let's create 10 of them at a very fast rate:

> For i in ' seq 1 10 '; Do curl-x post-h "Content-type:application/json"--data ' {names ': ' Make a Cake '} ' http://10.10.0.10:8880/api/v1/addTa Sk Done
This allows us to create 10 tasks in milliseconds (about 638 milliseconds). If there is no frequency limit, this is vulnerable to DOS attacks.

Now let's use the Laravel built-in frequency-limiting middleware to limit the number of requests/responses per minute. Use throttling middleware to wrap our API:

Route::group ([' prefix ' => ' API ', ' middleware ' => ' throttle:3,10 '], function () {

...

});
This limits individual IP requests only 3 times in every 10 minutes. When the same IP requests the API again, the following response is returned:

...

< X-ratelimit-limit:3

< x-ratelimit-remaining:0

< retry-after:599

...
Try too many times. The key to frequency limits is to find the right balance point. In our TODO application, for example, the 10-minute request is too restrictive 3 times, we can modify to create 3 tasks per minute (default is set 1 minutes, and if only set ' middleware ' => ' throttle ', will be 10 times/min):

Route::group ([' prefix ' => ' API ', ' middleware ' => ' throttle:3 '], function () {

...

});
Use a field other than IP to limit
Many organizations and ISPs use NAT ' d solutions. Therefore, it is not advisable to restrict the use of a group of people simply because one person abuses the API. If we want to use a unit other than IP to limit it, we just need to extend the Throttlerequests class and overwrite the method Resolverequestsignature ():

protected function Resolverequestsignature ($request)
{

if (! $request->route ()) {
throw new RuntimeException (' Unable to generate fingerprint. Route unavailable. ');
}

Return SHA1 (
Implode (' | '), $request->route ()->methods ()).
'|'. $request->route ()->domain ().
'|'. $request->route ()->uri ().
'|'. $request->ip ()//Replace this line
);
}
Replace the $request->ip () field with a different field, for example, SessionId as a unique key to add:

$request->session ()

Or use the USER_ID passed by request to restrict:

$request->input (' user_id ')

Or even use API KEY:

$request->header (' Api-key ')

The only requirement here is that the user is the only one.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.