Skip to content

Instantly share code, notes, and snippets.

@ervinne13
Last active September 25, 2018 02:31
Show Gist options
  • Save ervinne13/c4f94d285811519c872b2da3fd1b7a38 to your computer and use it in GitHub Desktop.
Save ervinne13/c4f94d285811519c872b2da3fd1b7a38 to your computer and use it in GitHub Desktop.
Middleware for Blocking access to routes unless IP is whitelisted.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class RequireIPIsWhitelisted
{
public function handle($request, Closure $next)
{
if (!$this->isRequestIpWhitelisted($request)) {
$this->logBlockedAccess($request);
abort(403, 'Access denied'); // you can also abort(404) so it's not so obvious that the route exists at all
}
return $next($request);
}
private function logBlockedAccess(Request $request): void
{
// create a separate "security" channel in your logging.php config file so security
// logs are written to a different location
$msg = "Access to admin only route requested by {$request->getClientIp()}, user was denied access.";
Log::channel('security')->warning($msg);
}
private function isRequestIpWhitelisted(Request $request): bool
{
return in_array($request->getClientIp(), $this->getWhitelistedIpList());
}
private function getWhitelistedIpList(): array
{
$ipListString = env('APP_WHITELISTED_IP_CSV');
return explode(',', $ipListString);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment