Skip to content

Instantly share code, notes, and snippets.

@janzell
Last active January 16, 2017 05:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janzell/5cc52a5b3455b374a193dc862a954e8a to your computer and use it in GitHub Desktop.
Save janzell/5cc52a5b3455b374a193dc862a954e8a to your computer and use it in GitHub Desktop.
Laravel ApiWhiteList Middleware
<?php namespace App\Http\Middleware;
use Closure;
use Config;
use App;
class ApiWhiteList
{
//List of API path you want to restrict the use based on their IP Addresses
protected $apiPath = [
'api/v1/partner',
'api/v1/partnerHarness'
];
/**
* ApiWhiteList constructor.
*/
public function __construct()
{
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @throws \HttpException
* @return mixed
*/
public function handle($request, Closure $next)
{
//check the if requested path exist on the API Path array
//validate client IP Address to the Whitelisted IP Addresses
if (in_array($request->path(), $this->apiPath) && !$this->isIpWhiteListed($request)) {
App::abort(403, 'Access denied');
}
return $next($request);
}
/**
* Is IP white listed
*
* @param object $request
* @return bool
*/
public function isIpWhiteListed($request)
{
//In this case, I used the APP_DEBUG variable under .env file to check which IPs should I used based on their environment.
return in_array($request->ip(),
( getenv('APP_DEBUG') == 'true') ? Config::get('ip.staging') : Config::get('ip.production')
);
}
}
<?php
/**
* @You should add this file under config/ip.php
*/
return [
'staging' => [
'112.199.116.18',
'112.199.116.19',
'124.107.67.135',
'184.169.129.472'
],
'production' => [
'112.199.116.18',
'112.199.116.19',
'124.107.67.135',
'184.169.129.472'
]
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment