Restrict Laravel API Routes/Calls by Allowing Server IP
Nowadays, security is the main issue for an application. Today I’m going to share an idea to restrict your API calls from the external websites. Only allowed certain server IP addresses can call the API.
Table of Contents
We will follow a few simple steps:
Step 1 : Create a Middleware
We have to create a IPMiddleware for our project. Run this artisan command to make the middleware:
php artisan make:middleware IPMiddleware
Step 2 : Configure the Middleware
Let’s configure the middleware. Open the app/Http/Middleware/IPMiddleware.php
file and paste this code:
<?php
namespace App\Http\Middleware;
use Closure;
use Response;
class IPMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$allowed_ip_addresses = "192.168.1.104, 127.0.0.1"; // add IP's by comma separated
$ipsAllow = explode(',', preg_replace('/\s+/', '', $allowed_ip_addresses));
// check ip is allowed
if (count($ipsAllow) >= 1) {
if (!in_array(request()->ip(), $ipsAllow)) {
// return response
return Response::json(array(
'success' => false,
'message' => 'You are blocked to call API!'
));
}
}
return $next($request);
}
}
In the IPMiddleware, insert your server IPs here:
$allowed_ip_addresses = "";
You can add more IP address by comma separated.
Step 3 : Add the Middleware to Kernel
Now we have to add the new middleware class in the $routeMiddleware
property of your app/Http/Kernel.php
class.
protected $routeMiddleware = [
-----
'IPCheck' => \App\Http\Middleware\IPMiddleware::class,
];
Step 4 : Apply Middelware to Routes
Our middleware is ready to use. Let’s apply this to our routes:
Route::group(['middleware' => ['IPCheck']], function () {
/* Here your routes */
Route::get('test', 'TestController@index');
});
Congrats! Now your API is more secure.
Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.