Allow Only Certain ip addresses to API in Laravel 5.8

By Hardik Savani | May 7, 2019 | | 5080 Viewer | Category : PHP Laravel


Today, we will learn how to restrict ip address in laravel api or web route. You can allow only particular ip address in laravel 5.8 application. we will create middleware that will check ip address is white listed then you can access api otherwise you will get error message.

we will give access only particular ip address using laravel middleware. laravel middleware provide way to prevent other ip address that want to access over secure api or url.

In this tutorial example, we will create one middleware as "CheckIpMiddleware" and we will use that middleware on every secure api and url. So just see bellow steps how to complete this things:

Create Middleware

In this step, we will create one middleware as "CheckIpMiddleware" using bellow command:

php artisan make:middleware CheckIpMiddleware

Now you can see created new file CheckIpMiddleware.php in Middleware directory. I created whiteIps array variable for white listed ip address. Only can access api or url that listed on that array. you need to update that as bellow:

app/Http/Middleware/CheckIpMiddleware.php

<?php

namespace App\Http\Middleware;

use Closure;

class CheckIpMiddleware

{

public $whiteIps = ['192.168.1.1', '127.0.0.1'];

/**

* Handle an incoming request.

*

* @param \Illuminate\Http\Request $request

* @param \Closure $next

* @return mixed

*/

public function handle($request, Closure $next)

{

if (!in_array($request->ip(), $this->whiteIps)) {

/*

You can redirect to any error page.

*/

return response()->json(['your ip address is not valid.']);

}

return $next($request);

}

}

Now we need to register this middleware with specific name. so let's register it by Kernel file.

app/Http/Kernel.php

protected $routeMiddleware = [

'auth' => \App\Http\Middleware\Authenticate::class,

'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,

'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,

'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,

......

'checkIp' => \App\Http\Middleware\CheckIpMiddleware::class,

];

Use Middleware

In this step, we will use "checkIp" middleware in api and web routes. i will create example for api and web routes how it is using. so let's see both example:

routes/api.php

Route::middleware(['checkIp'])->group(function () {

Route::post('users', 'UserController@index')

Route::post('posts', 'PostController@index')

});

routes/web.php

Route::get('my-web', ['middleware' => ['checkIp'], function () {

return view('test');

}]);

Now you can run your project and check

I hope it can help you...



***Do you want me hire for your Project Work? Then Contact US.


We are Recommending you: