Laravel ip allowlist request filter middleware

Temporary ip allow list in PHP framework Laravel

 1<?php
 2
 3namespace App\Http\Middleware;
 4
 5use Closure;
 6use Illuminate\Http\Request;
 7use Illuminate\Support\Facades\Cache;
 8use Illuminate\Support\Facades\Log;
 9use Symfony\Component\HttpFoundation\IpUtils;
10
11class IpAllowMiddleware
12{
13    /**
14     * Handle an incoming request.
15     *
16     * @param  \Illuminate\Http\Request $request
17     * @param  \Closure $next
18     * @return mixed
19     */
20    public function handle($request, Closure $next)
21    {
22        $this->setTrustProxy();
23        $clientIp = $request->getClientIp();
24        if (!$this->compareOrigin($clientIp)) {
25            Log::warning("The client ip is forbidden: " . $clientIp);
26            abort(403, 'Access denied');
27        }
28        return $next($request);
29    }
30
31    private function compareOrigin($ip): bool
32    {
33        if (trim($ip) == "") return false;
34        $ipAllowlist = env("IP_ALLOW_LIST", "127.0.0.1, 0.0.0.0/32,::1");
35        $ips = explode(",", $ipAllowlist);
36        $cachekey = md5($ip);
37        return Cache::rememberForever("IP:ALLOW:" . $cachekey, function () use ($ip, $ips) {
38            return IpUtils::checkIp($ip, $ips);
39        });
40    }
41
42    private function setTrustProxy()
43    {
44        $proxies = env("TRUST_PROXY_LIST", "0.0.0.0/32");
45        $proxiesArr = explode(",", $proxies);
46        Request::setTrustedProxies($proxiesArr, Request::HEADER_X_FORWARDED_ALL);
47    }
48}
  • set system environment when php launched
1         export IP_ALLOW_LIST="127.0.0.1,::1"
2         export TRUST_PROXY_LIST= "10.244.0.0/16,10.20.0.0/16"