Last active
September 25, 2018 02:31
-
-
Save ervinne13/c4f94d285811519c872b2da3fd1b7a38 to your computer and use it in GitHub Desktop.
Middleware for Blocking access to routes unless IP is whitelisted.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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